Java 8将给定的时间和时区转换为UTC时间 [英] Java 8 Convert given time and time zone to UTC time

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

问题描述

我有时间使用字符串类型:2015-01-05 17:00 ZoneId 澳大利亚/悉尼

I have a time with string type like: "2015-01-05 17:00" and ZoneId is "Australia/Sydney".

如何使用Java将此时间信息转换为对应的UTC时间8个日期时间API?

How can I convert this time information to the corresponding to UTC time using Java 8 datetime API?

还需要考虑DST的东西。

Also need to considering DST stuff.

推荐答案

您正在寻找Java8中的 ZonedDateTime 类 - 一个完整的日期时间,包含时区和已解析的UTC / Greenwich偏移量。在设计方面,该类应主要视为 LocalDateTime ZoneId 的组合。 ZoneOffset 是一条重要但次要的信息,用于确保班级代表即时,特别是在夏令时重叠期间。

You are looking for ZonedDateTime class in Java8 - a complete date-time with time-zone and resolved offset from UTC/Greenwich. In terms of design, this class should be viewed primarily as the combination of a LocalDateTime and a ZoneId. The ZoneOffset is a vital, but secondary, piece of information, used to ensure that the class represents an instant, especially during a daylight savings overlap.

例如:

ZoneId australia = ZoneId.of("Australia/Sydney");
String str = "2015-01-05 17:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime localtDateAndTime = LocalDateTime.parse(str, formatter);
ZonedDateTime dateAndTimeInSydney = ZonedDateTime.of(localtDateAndTime, australia );

System.out.println("Current date and time in a particular timezone : " + dateAndTimeInSydney);

ZonedDateTime utcDate = dateAndTimeInSydney.withZoneSameInstant(ZoneOffset.UTC);

System.out.println("Current date and time in UTC : " + utcDate);

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

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