2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > java转换utc时间 Java 8将给定的时间和时区转换为UTC时间

java转换utc时间 Java 8将给定的时间和时区转换为UTC时间

时间:2019-12-03 18:34:31

相关推荐

java转换utc时间 Java 8将给定的时间和时区转换为UTC时间

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

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

Also need to considering DST stuff.

解决方案

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.

For example:

ZoneId australia = ZoneId.of("Australia/Sydney");

String str = "-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);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。