gpt4 book ai didi

c - strptime 时间转换 - 年和月的值错误

转载 作者:行者123 更新时间:2023-12-02 04:45:20 25 4
gpt4 key购买 nike

我正在尝试使用 strptime() 将日期/时间字符串解析为其组件值。作为测试,我尝试使用以下代码解析固定日期时间字符串并打印结果值:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(void)
{
struct tm tm;
memset(&tm, 0, sizeof(struct tm));
strptime("2001/11/12 18:31:01", "%Y/%m/%d %H:%M:%S", &tm);
printf("year: %d; month: %d; day: %d;\n",
tm.tm_year, tm.tm_mon, tm.tm_mday);
printf("hour: %d; minute: %d; second: %d\n",
tm.tm_hour, tm.tm_min, tm.tm_sec);
exit(EXIT_SUCCESS);
}

我得到的输出是:

year: 101; month: 10; day: 12;
hour: 18; minute: 31; second: 1

其他值看起来不错,但年份和月份与输入不匹配 (2001/11/12 18:31:01)。这是为什么?

最佳答案

在 C 语言的 struct tm 中,年是自 1900 年以来的年数,月是从零开始的(0 = 一月)。

因此您的日期输出语句应该是:

printf("year: %d; month: %d; day: %d;\n",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);

ISO C11 7.25.1 Components of time 如此表述(尽管这种行为方式倒退):

The tm structure shall contain at least the following members, in any order. The semantics of the members and their normal ranges are expressed in the comments.

int tm_sec;     // seconds after the minute — [0, 60]
int tm_min; // minutes after the hour — [0, 59]
int tm_hour; // hours since midnight — [0, 23]
int tm_mday; // day of the month — [1, 31]
int tm_mon; // months since January — [0, 11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday — [0, 6]
int tm_yday; // days since January 1 — [0, 365]
int tm_isdst; // Daylight Saving Time flag

关于c - strptime 时间转换 - 年和月的值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19907059/

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