在 C/C++ 中在当地时间和 GMT/UTC 之间转换
在 C/C++ 中在本地时间和 UTC 之间转换日期时间的最佳方法是什么?
What's the best way to convert datetimes between local time and UTC in C/C++?
日期时间"是指包含日期和时间的一些时间表示.我会对 time_t
、struct tm
或任何其他使其成为可能的表示形式感到满意.
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.
这是我要解决的具体问题:我得到一对包含儒略日期和一天中的秒数的值.这些值在 GMT 中.我需要将其转换为本地时区YYYYMMDDHHMMSS"值.我知道如何将儒略日期转换为 Y-M-D,显然很容易将秒转换为 HHMMSS.然而,棘手的部分是时区转换.我确信我可以找到解决方案,但我更愿意找到一种标准"或众所周知"的方式,而不是四处走动.
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.
一个可能相关的问题是 获取夏令时转换C中时区的日期
A possibly related question is Get Daylight Saving Transition Dates For Time Zones in C
推荐答案
你应该使用 gmtime
/localtime
和 timegm
/mktime
.这应该为您提供在 struct 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.
如果你想在时区之间转换,你应该修改struct tm
的tm_gmtoff
.
If you're trying to convert between timezones, you should modify the struct tm
's tm_gmtoff
.
相关文章