Convert date to unix time stamp in C ++

As some websites that convert these unix timestamps say, print

2013/05/07 05:01:00 (yyyy/mm/dd, hh:mm:ss) is 1367902860.

As I do this in C ++, the brand is different from the date. Here is the code:

time_t rawtime;
struct tm * timeinfo;

int year=2013, month=5, day=7, hour = 5, min = 1, sec = 0;

/* get current timeinfo: */
time ( &rawtime ); //or: rawtime = time(0);
/* convert to struct: */
timeinfo = localtime ( &rawtime ); 

/* now modify the timeinfo to the given date: */
timeinfo->tm_year   = year - 1900;
timeinfo->tm_mon    = month - 1;    //months since January - [0,11]
timeinfo->tm_mday   = day;          //day of the month - [1,31] 
timeinfo->tm_hour   = hour;         //hours since midnight - [0,23]
timeinfo->tm_min    = min;          //minutes after the hour - [0,59]
timeinfo->tm_sec    = sec;          //seconds after the minute - [0,59]

/* call mktime: create unix time stamp from timeinfo struct */
date = mktime ( timeinfo );

printf ("Until the given date, since 1970/01/01 %i seconds have passed.\n", date);

Received Timestamp

1367899260, but not 1367902860.

What is the problem? Even if I switch to hour-1 or hour + 1, this does not match. EDIT: Well yes, if I add 1 hour, it works. previously also added from 1 to minutes.

+3
source share
5 answers

You should use timegm () instead of mktime () and that’s it. Because mktime is for localtime and timegm is for UTC / GMT time.

Convert between local times and GMT / UTC in C / C ++

+3
source

, ? tm:: tm_isdst - . , , , reset. , - , , - , 1 .

, . , tm:: tm_wday tm:: tm_yday mktime. http://www.cplusplus.com/reference/ctime/tm/ http://www.cplusplus.com/reference/ctime/mktime/

+1

mktime() , time_t, , . - 2013/05/07 05:01:00 UTC. 1367874060, 8 -. UTC + 8: 00, mktime() 2013/05/07 05:01:00 UTC + 8: 00, .

PS: localtime() struct tm. gmtime(), localtime() ctime() . struct tm.

0

localtime.

struct tm timeinfo;
...
timeinfo = *localtime(&rawtime);
...
date = mktime(&timeinfo);

, , localtime. mktime .

0

, - , UTC, - .

gmtime, localtime, UTC; , localtime, -, tm. tm; , localtime, , .

Unfortunately, mktimethere is no standard option using UTC. If you want UTC, your options are:

  • Set the time zone using setenv("TZ", "", 1);. Please note that this affects the entire program, so it can be inconvenient if you also need to deal with local time.
  • Use a library like Boost.DateTime, which handles dates and time intervals a bit better than C library.
0
source

All Articles