在Java中将本地时间戳转换为UTC时间戳

编程入门 行业动态 更新时间:2024-10-27 16:39:34
本文介绍了在Java中将本地时间戳转换为UTC时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个毫秒-since-local-epoch 时间戳,我想将它转换为毫秒-since-UTC-epoch 时间戳.快速浏览一下文档,看起来像这样可以工作:

I have a milliseconds-since-local-epoch timestamp that I'd like to convert into a milliseconds-since-UTC-epoch timestamp. From a quick glance through the docs it looks like something like this would work:

int offset = TimeZone.getDefault().getRawOffset(); long newTime = oldTime - offset;

有没有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

使用 Calendar 获取本地 Epoch 的偏移量,然后将其添加到本地 epoch 时间戳.

Use a Calendar to get what the offset was at the local Epoch, then add that to the local-epoch timestamp.

public static long getLocalToUtcDelta() { Calendar local = Calendar.getInstance(); local.clear(); local.set(1970, Calendar.JANUARY, 1, 0, 0, 0); return local.getTimeInMillis(); } public static long converLocalTimeToUtcTime(long timeSinceLocalEpoch) { return timeSinceLocalEpoch + getLocalToUtcDelta(); }

更多推荐

在Java中将本地时间戳转换为UTC时间戳

本文发布于:2023-10-19 07:18:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1506776.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   转换为   中将   Java   UTC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!