tm date 在 C++ 中输出错误的日期?

问题描述 投票:0回答:1

我有一个 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 日星期六。 我无法找出导致此问题的原因。

c++ date visual-c++ time calendar
1个回答
0
投票

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;
© www.soinside.com 2019 - 2024. All rights reserved.