I have char date[] = "2011-04-01"; How it convert to timestamp in C or C++ ?
2 Answers
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
-
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". Suggeststruct tm time = {0};
and usetime->isdst == -1;
. Commented Jan 26, 2017 at 18:16 -
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 );
-
Note that this solutions assume that
"2011-04-01"
is the local date and the DST is not in effect astmdate.tm_mday == 0
. Thustime_t t
may be 1 hour off from midnight. Commented Jan 26, 2017 at 18:09