我需要在C语言中转换时区之间的时间(在linux上,所以任何特定的东西都会这样做).
我知道我当前的时间,本地和UTC,我有目标时间的偏移量.我试图使用mktime,gmtime,localtime和类似的功能集,但仍然无法弄明白.
提前致谢.
由于评论不允许发布代码,因此单独发布答案.如果您知道"本地"时间和"UTC"时间,则可以计算"其他"时间与"本地"时间的偏移量.然后将struct tm转换为日历时间,添加所需的秒数(作为目标时间的偏移量),并将其转换回struct tm:
(编辑以说明使用mktime标准化的另一个场景)
#include#include #include #include int main(int argc, char *argv) { struct timeval tv_utc; struct tm *local_tm, *other_tm; /* 'synthetic' time_t to convert to struct tm for the other time */ time_t other_t_synt; /* Other time is 1 hour ahead of local time */ int other_local_delta = 1*3600; /* the below two lines are just to set local_tm to something */ gettimeofday(&tv_utc, NULL); local_tm = localtime(&tv_utc.tv_sec); printf("Local time: %s", asctime(local_tm)); #ifdef DO_NOT_WRITE_TO_LOCAL_TM other_t_synt = mktime(local_tm) + other_local_delta; #else local_tm->tm_sec += other_local_delta; /* mktime will normalize the seconds to a correct calendar date */ other_t_synt = mktime(local_tm); #endif other_tm = localtime(&other_t_synt); printf("Other time: %s", asctime(other_tm)); exit(0); }