2

I have char date[] = "2011-04-01"; How it convert to timestamp in C or C++ ?

2

2 Answers 2

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
2
  • 1
    Not 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;. Commented Jan 26, 2017 at 18:16
  • Where is it neccesary to use: "time->isdst == -1;" ?
    – Cristian
    Commented Mar 21, 2018 at 16:30
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 );
1
  • 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. Commented Jan 26, 2017 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.