Convert date to unix time stamp in c++
Solution 1
You must use timegm() instead of mktime(), and that's all. Because mktime is for localtime and timegm for UTC/GMT time.
Converting Between Local Times and GMT/UTC in C/C++
Solution 2
Do you have daylight saving time when you are from? The tm::tm_isdst parameter is a flag for daylight saving time. This will get filled by the localtime call based on where you are and the time of year and you do not reset it. So even if both you and the web page are using the same time, if you have the daylight saving flag set and the web page doesn't then you will end up different by 1 hour.
Note you don't really need the localtime call. You can just fill in all the parts manually because tm::tm_wday and tm::tm_yday are ignored by mktime. Check out http://www.cplusplus.com/reference/ctime/tm/ and http://www.cplusplus.com/reference/ctime/mktime/
user2366975
Updated on February 06, 2020Comments
-
user2366975 about 4 years
As some websites that convert those unix time stamps say, the stamp of
2013/05/07 05:01:00 (yyyy/mm/dd, hh:mm:ss) is 1367902860.
The way I do it in C++, the stamp differs 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);
The resulting time stamp is
1367899260, but not 1367902860.
What is the problem here? Even if I change to hour-1 or hour+1, it does not match. EDIT: Well yes if i add 1 to hour, it works. previously also added 1 to minutes.
-
user2366975 about 10 yearsNice idea, but it does not change anything.
-
user2366975 about 10 yearsI have changed to
timeinfo = gmtime ( &rawtime);
and the result remains the same. -
Mike Seymour about 10 years@user2366975: Oh yes,
mktime
will still assume local time, and it doesn't have a UTC version. -
mxmlnkn almost 7 yearsThere is no timegm in the C++ STL.
-
Alexis Wilke about 6 years@mxmlnkn There is
mktime()
in C++ STL, is there?! -
mxmlnkn about 6 years