gpt4 book ai didi

将字符串时间转换为秒

转载 作者:行者123 更新时间:2023-12-04 06:33:34 26 4
gpt4 key购买 nike

这是我将字符串时间转换为日期时间格式并将秒转换为秒的代码,但它显示了一些奇怪的值。请帮助我

代码:

struct tm tm;
time_t t;
char s[25]="Sat Feb 19 12:53:39 2011";
if (strptime(s, "%A %b %d %H:%M:%S %Y", &tm) != NULL)


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);
printf("week day: %d; year day: %d\n", tm.tm_wday, tm.tm_yday);

tm.tm_isdst = -1;
t = mktime(&tm);
printf("seconds since the Epoch: %ld\n", (long) t);

输出是

year: 111; month: 1; day: 19;

hour: 12; minute: 53; second: 40

week day: 6; year day: 49

seconds since the Epoch: 1298102020

最佳答案

来自 http://en.wikipedia.org/wiki/Time.h :

C 标准库中的日历时间(也称为“故障时间”)表示为 struct tm 结构,由以下成员组成:

Member  Description
int tm_hour hour (0 – 23)
int tm_isdst Daylight saving time enabled (> 0), disabled (= 0), or unknown (< 0)
int tm_mday day of the month (1 – 31)
int tm_min minutes (0 – 59)
int tm_mon month (0 – 11, 0 = January)
int tm_sec seconds (0 – 60, 60 = Leap second)
int tm_wday day of the week (0 – 6, 0 = Sunday)
int tm_yday day of the year (0 – 365)
int tm_year year since 1900

即您需要将 1900 添加到年份,并且月份是从零开始的。

关于将字符串时间转换为秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5119059/

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