如何使用 ZonedDateTime 或 Java 8 将任何日期时间转换为 UTC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34115801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert any Date time to UTC using ZonedDateTime or Java 8
提问by Bilal Shah
I am trying to convert date 06-12-2015 02:10:10 PM
from default zone to UTC using ZonedDateTime
.
我正在尝试使用 将日期06-12-2015 02:10:10 PM
从默认区域转换为 UTC ZonedDateTime
。
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
ZonedDateTime utc = ZonedDateTime.of(localDateTime, ZoneOffset.UTC);
but utc
returns 2015-12-06T14:10:10Z
instead of 06-12-2015 09:10:10 AM
但utc
返回2015-12-06T14:10:10Z
而不是06-12-2015 09:10:10 AM
How can I convert date from default zone to UTC? The answer given hereconvert current time to UTC.
如何将日期从默认区域转换为 UTC?此处给出的答案将当前时间转换为 UTC。
采纳答案by Elliott Frisch
You can use ZonedDateTime.ofInstant(Instant, ZoneId)
where the second parameter is UTC
(the instant knows the local offset). Something like,
您可以使用ZonedDateTime.ofInstant(Instant, ZoneId)
第二个参数所在的位置UTC
(即刻知道本地偏移量)。就像是,
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