我想將日期時間字符串保存到time_t,然後將其轉換回原來的字符串。將字符串轉換爲time_t,然後將time_t轉換回字符串
但下面將輸出"2016-04-25_10:10:05"
代碼和小時輸出將通過改變date_str
不正確。
如果將代碼更改爲std::string date_str = "1470-04-25_09:10:05";
, ,結果將會更正。
下面是代碼:
#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;
}
時區問題?你在什麼時區?夏令時?你有沒有檢查過'tm'結構的細節(例如在調試器中)? –
1小時的差距是有道理的...我沒有得到的是1470年。 – pah
@JoachimPileborg它在同一臺機器上。但如何使它獨立於時區。 – Christophe