views:

66

answers:

4

I have a a long which has the time in UTC format as a timestamp for some data, now I want to convert it to this format: month 1-12 Day 1-31 24 Hour format 0-23 minute 0-59 second 0-59 subsecond nanoseconds 0-999,999,999

now the nanoseconds can obviously be set to 0 as it doesnt need to be that accurate.

What is the best method to do this? I've seen loads of examples but they are confusing and don't seem to work for converting an arbitary date, they only work for converting the exact time at that moment.

Thanks! :)

A: 

gmtime(3)

Nikolai N Fetissov
A: 

You may want to look into ctime header. asctime, strftime, ctime etc converts time to string.

Donotalo
A: 

Here you go. Note the commented lines

#include <stdio.h>
#include <time.h>

int main(void) {
  char buf[512];
  long stamp = 1287055578;
  struct tm x;
  time_t cstamp = stamp;       /* 1 */
  x = *gmtime(&cstamp);        /* 2 */

  sprintf(buf, "month %d Day %d 24 Hour format %d minute %d second %d "
               "subsecond nanoseconds 0",
               x.tm_mon + 1, x.tm_mday, x.tm_hour, x.tm_min, x.tm_sec);

  printf("%s\n", buf); /* long converted to string */
  return 0;
}

1) gmtime takes a value of type time_t*, so I implicitly convert the long to time_t and pass that address in the next step

2) gmtime returns a pointer to a struct tm object. Dereference that pointer and copy the object to my local x variable

Instead of gm_time, you may want to use localtime and have the library functions deal with time zones and daylight saving time issues.

pmg
Great answer, thanks.
rolls
A: 

thanks for the answers everyone, I ended up doing it this way

long UTCInSeconds = ...

struct tm * local;
local = localtime(UTCInSeconds);

Month = local->tm_mon + 1;
Day = local->tm_mday;
Year = local->tm_year + 1900;
Hour = local->tm_hour;
Minute = local->tm_min;
Second = local->tm_sec;
rolls