3

I'm trying to convert a date string to a time_t, but mktime() is returning seemingly random dates:

string datetime = "2014-12-10 10:30";
struct tm tmInfo;
strptime(datetime.c_str(), "%Y-%m-%d %H:%M", &tmInfo);
tmInfo.tm_isdst = 0;
time_t eventTime = mktime(&tmInfo);

eventTime ranges wildly from the 1970s to the 2030s. The tmInfo struct holds the correct date, so the error must be happening in mktime(). Any ideas of what's going wrong?

holdennb
  • 35
  • 1
  • 4
  • Seems to [work for me](http://rextester.com/FRRQ10057). `eventTime` comes out as `1418203800` which is in the right ballpark. – Igor Tandetnik Dec 08 '14 at 04:11

3 Answers3

8

You need to properly zero-initialize all of the other fields of the struct tm instance before calling strptime(), since it doesn't necessarily initialize every field. From the strptime() POSIX specification:

It is unspecified whether multiple calls to strptime() using the same tm structure will update the current contents of the structure or overwrite all contents of the structure. Conforming applications should make a single call to strptime() with a format and all data needed to completely specify the date and time being converted.

For example, this should suffice:

struct tm tmInfo = {0};
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • Setting tmInfo to { 0 } beforehand worked, thank you! I accepted your answer because of the explanation. – holdennb Dec 08 '14 at 04:22
4

You have to initialize the struct to 0 beforehand or also input the seconds:

string datetime = "2014-12-10 10:30";
struct tm tmInfo = { 0 };
strptime(datetime.c_str(), "%Y-%m-%d %H:%M", &tmInfo);

or

string datetime = "2014-12-10 10:30:00";
struct tm tmInfo;
strptime(datetime.c_str(), "%Y-%m-%d %H:%M:%S", &tmInfo);
2501
  • 25,460
  • 4
  • 47
  • 87
0

The below code would do the work, if you want current system time in an format

 time_t current_time;
 struct tm *loctime;

 memset(buffer,0,strlen(buffer));
 current_time = time(NULL);
 loctime = localtime(&current_time);
 strftime(buffer,250,"--> %d/%m/%y  %H:%M:%S",loctime);
ash123
  • 53
  • 9