gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:15:15 27 4
gpt4 key购买 nike

我想将日期时间字符串保存到 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”案例中的一小时间隔,这是因为您没有设置 tm.tm_isdstmktime() 调用之前:

/* 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.

关于c++ - 将字符串转换为 time_t,然后将 time_t 转换回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38780192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com