I have char date[] = "2011-04-01"; How it convert to timestamp in C or C++ ?
Asked
Active
Viewed 1.4k times
2
-
2Maybe this answer can help: http://stackoverflow.com/questions/1002542/how-to-convert-datetime-to-unix-timestamp-in-c – MD Sayem Ahmed Apr 22 '11 at 10:01
-
Your title says C, your question says C or C++, and you tagged just C++. Are you programming in C, or programming in C++? – Puppy Apr 22 '11 at 10:36
2 Answers
7
Warning: strptime is a POSIX-function (may not be available through time.h on OS "Windows" platform).
#include <time.h>
struct tm time;
strptime("2011-04-01", "%Y-%m-%d", &time);
time_t loctime = mktime(&time); // timestamp in current timezone
time_t gmttime = timegm(&time); // timestamp in GMT

blaze
- 4,326
- 18
- 23
-
1Not fully initializing/assigning `time` can be a problem: "unspecified ... will update the current contents of the structure or overwrite all contents of the structure". Suggest `struct tm time = {0};` and use `time->isdst == -1;`. – chux - Reinstate Monica Jan 26 '17 at 18:16
-
3
Try this:
char date[] = "2011-04-01";
date[4] = date[7] = '\0';
struct tm tmdate = {0};
tmdate.tm_year = atoi(&date[0]) - 1900;
tmdate.tm_mon = atoi(&date[5]) - 1;
tmdate.tm_mday = atoi(&date[8]);
time_t t = mktime( &tmdate );

Blazes
- 4,721
- 2
- 22
- 29
-
Note that this solutions assume that `"2011-04-01"` is the _local_ date and the DST is _not_ in effect as `tmdate.tm_mday == 0`. Thus `time_t t` may be 1 hour off from midnight. – chux - Reinstate Monica Jan 26 '17 at 18:09