本地时间和GMT / UTC之间的转换在C / C ++ [英] Converting Between Local Times and GMT/UTC in C/C++
问题描述
什么是转换用C本地时间和UTC / C ++?
What's the best way to convert datetimes between local time and UTC in C/C++?
通过日期时间,我的意思是包含日期和时间的日一段时间再presentation。我会很乐意与 time_t的
,结构TM
,或任何其他重presentation,使之成为可能。
By "datetime", I mean some time representation that contains date and time-of-day. I'll be happy with time_t
, struct tm
, or any other representation that makes it possible.
我的平台是Linux操作系统。
My platform is Linux.
下面是我试图解决具体的问题:我找一双含Julian日期和若干秒到一天的值。这些值都在GMT。我需要将其转换成一个本地时区YYYYMMDDHHMMSS的价值。我知道如何Julian日期为Y-M-D转换,显然很容易秒转换为HHMMSS。但是,棘手的部分是时区转换。我敢肯定,我可以想出一个解决方案,但我想preFER找到一个标准或知名的方式,而不是绊脚石左右。
Here's the specific problem I'm trying to solve: I get a pair of values containing a julian date and a number of seconds into the day. Those values are in GMT. I need to convert that to a local-timezone "YYYYMMDDHHMMSS" value. I know how to convert the julian date to Y-M-D, and obviously it is easy to convert seconds into HHMMSS. However, the tricky part is the timezone conversion. I'm sure I can figure out a solution, but I'd prefer to find a "standard" or "well-known" way rather than stumbling around.
一个可能相关的问题是<一个href=\"http://stackoverflow.com/questions/678445/get-daylight-saving-transition-dates-for-time-zones-in-c\">Get夏令过渡日期时区用C
A possibly related question is Get Daylight Saving Transition Dates For Time Zones in C
推荐答案
你应该使用组合 gmtime的
/ 本地时间
和 timegm
/ mktime
。这应该给你正交工具做之间的转换结构TM
和 time_t的
。
You're supposed to use combinations of gmtime
/localtime
and timegm
/mktime
. That should give you the orthogonal tools to do conversions between struct tm
and time_t
.
有关UTC / GMT:
For UTC/GMT:
time_t t;
struct tm tm;
struct tm * tmp;
...
t = timegm(&tm);
...
tmp = gmtime(t);
有关本地时间:
t = mktime(&tm);
...
tmp = localtime(t);
所有 tzset()
是否设置为从 TZ
环境变量中的内部时区变量。我不认为这是应该被称为一次以上。
All tzset()
does is set the internal timezone variable from the TZ
environment variable. I don't think this is supposed to be called more than once.
如果你想时区之间进行转换,您应该修改结构TM
的 tm_gmtoff
。
If you're trying to convert between timezones, you should modify the struct tm
's tm_gmtoff
.
这篇关于本地时间和GMT / UTC之间的转换在C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!