Java 8 Convert given time and time zone to UTC time

前端 未结 3 1110
[愿得一人]
[愿得一人] 2020-12-12 22:53

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

How can I convert this time info

3条回答
  •  离开以前
    2020-12-12 23:38

    An alternative to the existing answer is to setup the formatter with the appropriate time zone:

    String input = "2015-01-05 17:00";
    ZoneId zone = ZoneId.of("Australia/Sydney");
    
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(zone);
    ZonedDateTime utc = ZonedDateTime.parse(input, fmt).withZoneSameInstant(UTC);
    

    Since you want to interact with a database, you may need a java.sql.Timestamp, in which case you don't need to explicitly convert to a UTC time but can use an Instant instead:

    ZonedDateTime zdt = ZonedDateTime.parse(input, fmt);
    Timestamp sqlTs = Timestamp.from(zdt.toInstant());
    

提交回复
热议问题