简体   繁体   English

将Unix time_t转换为任意时区的最佳方法?

[英]Best way to convert Unix time_t to/from abitrary timezones?

My code receives a time_t from an external source. 我的代码从外部来源收到time_t。 However, that time_t isn't acutally based on UTC Epoch time, along with it I get a timezone string (eg, EDT, PST, etc), and its based on this offset'ed epoch. 但是,该time_t并非完全基于UTC纪元时间,因此我得到了一个时区字符串(例如EDT,PST等),并且它基于此offset'ed纪元。 I need to convert this to a true UTC Epoch based time_t. 我需要将其转换为基于time_t的真实UTC纪元。

Additionally, I need to be able to go in the opposite direction, taking a UTC Epoch based time_t and a timezone, and create the offsetted time_t, but in this situation instead of having a timezone like EDT/PST), etc, I have a Unix style timezone description like "America/New York" and need to convert to the correct timezone given daylight savings, so I'd need to get back from the algorithm, both an offsetted time_t, and the correct descriptor (EDT,EST). 此外,我需要能够朝相反的方向前进,以基于UTC纪元的time_t和时区为基础,并创建偏移的time_t,但是在这种情况下,我不必像EDT / PST这样的时区了,等等。 Unix风格的时区描述,例如“ America / New York”,并且需要根据夏时制转换为正确的时区,因此我需要从算法中获取偏移的time_t和正确的描述符(EDT,EST)。

I'm pretty sure I can pull this off by temporarily changing tzset() and some combination of conversions between broken-down time, time_t and timeval, but doing this always makes my brain hurt and makes me feel like I'm missing something obvious. 我很确定我可以通过临时更改tzset()以及分解时间,time_t和timeval之间的某种转换组合来实现这一目标,但是这样做总是使我的大脑受伤,并使我感到自己缺少明显的东西。 Can anyone recommend some code or sudo-code to do this or at least a proper approach? 谁能推荐一些代码或sudo代码来做到这一点,或者至少是一种适当的方法?

time_t is in seconds, so just offset your time_t values by 3600 times the number of hours the timezone is offset by. time_t以秒为单位,因此只需将您的time_t值偏移时区所偏移的小时数的3600倍即可。 As long as you have the offset specifically identified (ie EST or EDT instead of US/Eastern or EST5EDT or whatnot) then this is really simple and not prone to errors. 只要您有专门确定的偏移量(即EST或EDT而不是US / Eastern或EST5EDT或其他),这确实很简单并且不容易出错。

would any of these functions help you? 这些功能对您有帮助吗? localtime(), gmtime(), etc. localtime(),gmtime()等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM