-3

I need to understand how to convert a date/time (obtained from a server) to a UNIX timestamp. I will be coding in C. Any ideas on how this might be done, or perhaps someone guide me to similar existing code?

Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28
Sujatha
  • 143
  • 1
  • 4
  • 11
  • You need to be more specific about what server you are talking about. – Harald May 10 '14 at 05:50
  • From where do you get your DATE TIME and in which format? Your question is being downvoted for lack of clarity. See http://stackoverflow.com/questions/1002542/how-to-convert-datetime-to-unix-timestamp-in-c – Tarik May 10 '14 at 05:51

1 Answers1

-1

See the db_unix_timestamp() function found here: http://svn.cubrid.org/cubridengine/trunk/src/query/string_opfunc.c


Here is a way that might work for you:

{
char *dateTimeString =  "2014-05-10 15:50:49"; //"YYYY-MM-DD HH:MM:SS"
struct tm t;
time_t t_of_day;
char *cp = dateTimeString;


t.tm_year  = strtol(cp, &cp, 10);      // 2011-1900;
t.tm_mon   = strtol(++cp, &cp, 10);    // Month, 0 - jan
t.tm_mday  = strtol(++cp, &cp, 10);    // Day of the month
t.tm_hour  = strtol(++cp, &cp, 10);
t.tm_min   = strtol(++cp, &cp, 10);
t.tm_sec   = strtol(++cp, &cp, 10);
t.tm_isdst = -1;                       // Is DST on? 1 = yes, 0 = no, -1 = unknown

t_of_day = mktime(&t);
printf("seconds since the Epoch: %ld\n", (long) t_of_day)
}
Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28
  • The date and time format will be in string "YYYY-MM-DD HH:MM:SS", and unix timestamp has to handle leap years also. How has to be done this? – Sujatha May 10 '14 at 10:00
  • @Sujatha, There are many ways to parse the string "YYYY-MM-DD HH:MM:SS" into it's individual numerical components. I modified the answer to show a way to do it using 'strtol()'; but you might also consider other string parsing methods, such as 'sscanf()', etc. – Mahonri Moriancumer May 10 '14 at 21:54
  • @Sujatha, as far as leap year goes, the 'mktime()' function includes leap-year in it's conversion to UNIX timestamp. If you want to know how 'mktime()' works, you might consider asking that in a new/separate question. – Mahonri Moriancumer May 10 '14 at 21:58
  • This approach would only work if the server returns a time in the same time zone as you, which, all things being considered, is probably unlikely. `strptime()` is also a much more elegant way of doing this than parsing it manually. It's POSIX-only, rather than ISO C, but then so is assuming `mktime()` returns "seconds since the Epoch", and assuming that `time_t` is an integral type. You're also not interpreting the `tm_year` and `tm_mon` members correctly, even though the comments suggest you know you should be. – Crowman May 10 '14 at 22:12