How to convert any Date time to UTC using ZonedDateTime or Java 8

前端 未结 1 1650
眼角桃花
眼角桃花 2020-12-31 16:11

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

LocalDateTime localDateTime = Loc         


        
1条回答
  •  有刺的猬
    2020-12-31 16:53

    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
    

    0 讨论(0)
提交回复
热议问题