这是一个简单的问题,但解决方案似乎远非简单.我想知道如何从UTC转换为本地时间.我正在寻找一个标准的C解决方案,或多或少保证可以在任何位置的任何计算机上工作.
我仔细阅读了以下链接,但我找不到解决方案:
我尝试了很多变体,例如(datetime是一个带有时间和日期的字符串,以UTC表示):
strptime(datetime, "%A %B %d %Y %H %M %S", tp);
strftime(printtime, strlen(datetime), "%A %B %d %Y %H %M %S", tp);
Run Code Online (Sandbox Code Playgroud)
要么
strptime(datetime, "%A %B %d %Y %H %M %S", tp);
lt=mktime(tp);
printtime=ctime(<);
Run Code Online (Sandbox Code Playgroud)
无论我尝试什么,printtime最终都与UTC相同.
编辑11-29-2013:基于下面"R"的非常有用的答案,我终于开始创建一个工作示例.我发现它在我测试它的两个时区中正常工作,CET和PST:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
long long diff_tm(struct tm *a, struct tm *b)
{
return a->tm_sec - b->tm_sec
+60LL*(a->tm_min - b->tm_min)
+3600LL*(a->tm_hour - b->tm_hour)
+86400LL*(a->tm_yday - b->tm_yday)
+(a->tm_year-70)*31536000LL
-(a->tm_year-69)/4*86400LL
+(a->tm_year-1)/100*86400LL
-(a->tm_year+299)/400*86400LL
-(b->tm_year-70)*31536000LL
+(b->tm_year-69)/4*86400LL
-(b->tm_year-1)/100*86400LL
+(b->tm_year+299)/400*86400LL;
}
int main()
{
time_t …Run Code Online (Sandbox Code Playgroud)