将 Unix time_t 与任意时区相互转换的最佳方法?

发布于 2024-09-10 23:57:35 字数 441 浏览 3 评论 0原文

我的代码从外部源接收 time_t 。然而,time_t 实际上并不是基于 UTC 纪元时间,随之我得到一个时区字符串(例如,EDT、PST 等),并且它基于这个偏移纪元。我需要将其转换为真正的基于 UTC Epoch 的 time_t。

此外,我需要能够朝相反的方向前进,采用基于 UTC 纪元的 time_t 和时区,并创建偏移的 time_t,但在这种情况下,我没有像 EDT/PST 这样的时区,等等, Unix 风格的时区描述,如“美国/纽约”,需要根据夏令时转换为正确的时区,因此我需要从算法中返回偏移的 time_t 和正确的描述符(EDT、EST)。

我很确定我可以通过临时更改 tzset() 以及分解时间、time_t 和 timeval 之间的转换组合来实现这一目标,但这样做总是让我的大脑受伤,让我觉得我错过了一些明显的东西。任何人都可以推荐一些代码或 sudo 代码来执行此操作,或者至少推荐一个正确的方法吗?

My code receives a time_t from an external source. 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. I need to convert this to a true UTC Epoch based time_t.

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).

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. Can anyone recommend some code or sudo-code to do this or at least a proper approach?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

━╋う一瞬間旳綻放 2024-09-17 23:57:35

time_t 以秒为单位,因此只需将 time_t 值偏移时区偏移小时数的 3600 倍即可。只要您有明确标识的偏移量(即 EST 或 EDT 而不是 US/Eastern 或 EST5EDT 等),那么这非常简单并且不容易出错。

time_t is in seconds, so just offset your time_t values by 3600 times the number of hours the timezone is offset by. As long as you have the offset specifically identified (i.e. EST or EDT instead of US/Eastern or EST5EDT or whatnot) then this is really simple and not prone to errors.

仅此而已 2024-09-17 23:57:35

这些功能对您有帮助吗? localtime()、gmtime() 等

would any of these functions help you? localtime(), gmtime(), etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文