How to convert any Date time to UTC using ZonedDat

2019-02-14 20:03发布

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);

but utc returns 2015-12-06T14:10:10Z instead of 06-12-2015 09:10:10 AM

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

1条回答
smile是对你的礼貌
2楼-- · 2019-02-14 20:16

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
查看更多
登录 后发表回答