Reputation: 305
I want to save a date time string to time_t and then convert it back to exactly original string.
But the code below will output "2016-04-25_10:10:05"
And the hour in the output will be incorrect by changing the date_str
.
If you change the code to std::string date_str = "1470-04-25_09:10:05";
,
the result will correct.
Here is the code:
#include <iostream>
#include <ctime>
#include <string>
#include <sstream>
#include <iomanip>
int main()
{
// try changing year, hour will be incorrect
std::string date_str = "2016-04-25_09:10:05";
std::tm tm{};
std::istringstream str_stream(date_str);
str_stream >> std::get_time(&tm, "%Y-%m-%d_%T");
std::time_t time = std::mktime(&tm);
std::stringstream stream;
stream << std::put_time(std::localtime(&time), "%F_%T");
std::cout << stream.str() << std::endl;
}
Upvotes: 2
Views: 2853
Reputation: 4778
Daylight Saving Time (DST) is used to save energy and make better use of daylight. It was first used in 1908 in Thunder Bay, Canada.
This explains why any year that you pass prior to 1908 (or prior to the year your timezone adopted DST) will affect the hour.
Also, answering to the one hour gap on the "2016-04-25_10:10:05
" case, this is because you're not setting tm.tm_isdst
prior to mktime()
call:
/* Assuming that all tm memory is set to 0 prior to this */
tm.tm_isdst = -1; /* mktime() will figure out the DST */
std::time_t time = std::mktime(&tm);
According to POSIX-1003.1-2001:
A positive or 0 value for tm_isdst shall cause mktime() to presume initially that Daylight Savings Time, respectively, is or is not in effect for the specified time. A negative value for tm_isdst shall cause mktime() to attempt to determine whether Daylight Savings Time is in effect for the specified time.
Upvotes: 2