gpt4 book ai didi

C 时差

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:28 29 4
gpt4 key购买 nike

我试图在 C 中区分两个日期,但我收到这样的输出:

future date: 18-11-2013 22:8

current date: 18-11-2013 22:8

这是我的代码:

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

int main(int argc, char *argv[])
{
// 2 years ahead
time_t unixtime = time(NULL);
struct tm *future = localtime(&unixtime);
future->tm_year += 2;

// current time
time_t unixtime_now = time(NULL);
struct tm *current = localtime(&unixtime_now);

printf("future date: %d-%d-%d %d:%d\n", future->tm_mday, 1 + future->tm_mon, 1900 + future->tm_year, future->tm_hour, future->tm_min);
printf("current date: %d-%d-%d %d:%d\n", current->tm_mday, 1 + current->tm_mon, 1900 + current->tm_year, current->tm_hour, current->tm_min);

return 0;
}

最佳答案

localtime 的返回值是指向静态分配结构的指针,该结构可能会被进一步调用日期/时间函数覆盖。如果您想将指向的数据保留更长时间,您需要复制它,或使用其他函数,例如 localtime_r

参见 localtime(3) man page :

The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone. The function acts as if it called tzset(3) and sets the external variables tzname with information about the current timezone, timezone with the difference between Coordinated Universal Time (UTC) and local standard time in seconds, and daylight to a nonzero value if daylight savings time rules apply during some part of the year. The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions. The localtime_r() function does the same, but stores the data in a user-supplied struct. It need not set tzname, timezone, and daylight.

关于C 时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20057990/

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