将字符串转换为 time_t,然后将 time_t 转换回字符串

convert string to time_t and then convert time_t back to string

我想将日期时间字符串保存到 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;
}

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.

这解释了为什么在 1908 年之前(或在您的时区采用 DST 的那一年之前)过去的任何年份都会影响小时。

此外,回答“2016-04-25_10:10:05”案例中的一小时间隔,这是因为您没有在 mktime() 调用之前设置 tm.tm_isdst

/* 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);

根据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.