我有一个 C++ 程序:
std::tm date{};
date.tm_year = 2023 - 1900;
date.tm_wday = 0;
date.tm_yday = (50 - 1) * 7;
std::mktime(&date);
std::cout << std::put_time(&date, "%A, %B %d, %Y") << std::endl;
我希望它输出今天的日期,即 2023 年 12 月 10 日星期日,但它输出的是 2022 年 12 月 31 日星期六。 我无法找出导致此问题的原因。
std::mktime()
不使用 tm::tm_wday
或 tm::tm_yday
字段作为输入,仅作为输出。您需要传入 tm::tm_mon
和 tm::tm_mday
字段,以及 tm::tm_isdst
字段,因为您是从当地时间转换的。
std::put_time()
期望来自 std::tm
或
std::localtime()
的
std::gmttime()
,而不是来自 std::mktime()
。
这是来自 cppreference.com 上的
std::mktime()
文档的示例:
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
int main()
{
setenv("TZ", "/usr/share/zoneinfo/America/Los_Angeles", 1); // POSIX-specific
std::tm tm{}; // Zero initialise
tm.tm_year = 2020 - 1900; // 2020
tm.tm_mon = 2 - 1; // February
tm.tm_mday = 15; // 15th
tm.tm_hour = 10;
tm.tm_min = 15;
tm.tm_isdst = 0; // Not daylight saving
std::time_t t = std::mktime(&tm);
std::tm local = *std::localtime(&t);
std::cout << "local: " << std::put_time(&local, "%c %Z") << '\n';
}
std::time()
而不是 std::mktime()
:
std::time_t t = std::time(nullptr);
std::tm date = *std::localtime(&t);
std::cout << std::put_time(&date, "%A, %B %d, %Y") << std::endl;