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;
}