将本地时间戳转换为UTC时间戳 [英] Converting local timestamp to UTC timestamp in Java

查看:265
本文介绍了将本地时间戳转换为UTC时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个毫秒从本地时代的时间戳,我想转换成一个毫秒从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;

有没有更好的方法?

推荐答案

使用日历获取本地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();
}

这篇关于将本地时间戳转换为UTC时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆