如何使用ZonedDateTime或Java 8将任何日期时间转换为UTC [英] How to convert any Date time to UTC using ZonedDateTime or Java 8

查看:3194
本文介绍了如何使用ZonedDateTime或Java 8将任何日期时间转换为UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 06-12-2015 02:10:10 PM 从默认区域转换为UTC使用 ZonedDateTime

I am trying to convert date 06-12-2015 02:10:10 PM from default zone to UTC using ZonedDateTime.

LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
ZonedDateTime utc = ZonedDateTime.of(localDateTime, ZoneOffset.UTC);

utc 返回 2015-12-06T14:10:10Z 而不是 06-12-2015 09:10:10 AM

如何将日期从默认区域转换为UTC? 此处的答案将当前时间转换为UTC。

How can I convert date from default zone to UTC? The answer given here convert current time to UTC.

推荐答案

您可以使用 ZonedDateTime.ofInstant(Instant,ZoneId) 其中第二个参数是 UTC (即时知道本地偏移量)。像

You can use ZonedDateTime.ofInstant(Instant, ZoneId) where the second parameter is UTC (the instant knows the local offset). Something like,

String source = "06-12-2015 02:10:10 PM";
String pattern = "MM-dd-yyyy hh:mm:ss a";
DateFormat sdf = new SimpleDateFormat(pattern);
try {
    Date date = sdf.parse(source);
    ZonedDateTime zdt = ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of("UTC"));
    System.out.println(zdt.format(DateTimeFormatter.ofPattern(pattern)));
} catch (ParseException e) {
    e.printStackTrace();
}

我得到(对应于我的本地区域偏移)

And I get (corresponding to my local zone offset)

06-12-2015 06:10:10 PM

这篇关于如何使用ZonedDateTime或Java 8将任何日期时间转换为UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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