用C时区之间的转换 [英] Converting between timezones in C

查看:647
本文介绍了用C时区之间的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用C时区之间转换的时间(在Linux,所以具体的事情会做太)。

I need to convert time between timezones in C (on linux, so anything specific would do too).

我知道我的当前时间,本地和UTC,我的目标时间偏移。我试图用mktime,gmtime的,本地时间和组类似的功能,但仍然无法搞清楚。

I know my current time, local and UTC, I have the offset of the target time. I am trying to use mktime, gmtime, localtime and similar set of functions but still can't figure it out.

先谢谢了。

推荐答案

由于意见不允许张贴code,张贴作为一个单独的答案。如果你知道本地时间和UTC的时候,你可以计算出从你的本地时间偏移的其他的时间。然后你转换结构TM为日历时间,加秒所需的数量(即的目标时间偏移),并将其转换回结构TM

As comments do not allow posting the code, posting as a separate answer.. If you know "local" time and "UTC" time, you can calculate the offset of the "other" time from your "local" time. Then you convert the struct tm into calendar time, add the desired number of seconds (being the offset of the target time), and convert it back to struct tm:

(编辑以考虑另一个方案中使用mktime的规范化)

(edited to account for another scenario to use mktime's normalization)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>

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);
}

这篇关于用C时区之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆