How to convert ZonedDateTime to Date?

后端 未结 9 684
无人共我
无人共我 2020-12-04 09:19

I am trying to set a server agnostic date time in my database and I believe the best practice to do so is to set a UTC DateTime. My db server is Cassandra and the db driver

9条回答
  •  暖寄归人
    2020-12-04 09:57

    The accepted answer did not work for me. The Date returned is always the local Date and not the Date for the original Time Zone. I live in UTC+2.

    //This did not work for me
    Date.from(java.time.ZonedDateTime.now().toInstant()); 
    

    I have come up with two alternative ways to get the correct Date from a ZonedDateTime.

    Say you have this ZonedDateTime for Hawaii

    LocalDateTime ldt = LocalDateTime.now();
    ZonedDateTime zdt = ldt.atZone(ZoneId.of("US/Hawaii"); // UTC-10
    

    or for UTC as asked originally

    Instant zulu = Instant.now(); // GMT, UTC+0
    ZonedDateTime zdt = zulu.atZone(ZoneId.of("UTC"));
    

    Alternative 1

    We can use java.sql.Timestamp. It is simple but it will probably also make a dent in your programming integrity

    Date date1 = Timestamp.valueOf(zdt.toLocalDateTime());
    

    Alternative 2

    We create the Date from millis (answered here earlier). Note that local ZoneOffset is a must.

    ZoneOffset localOffset = ZoneOffset.systemDefault().getRules().getOffset(LocalDateTime.now());
    long zonedMillis = 1000L * zdt.toLocalDateTime().toEpochSecond(localOffset) + zdt.toLocalDateTime().getNano() / 1000000L;
    Date date2 = new Date(zonedMillis);
    

提交回复
热议问题