javadatetimejava-8

OffsetDateTime to milliseconds


I want to know if there is a way to convert java.time.OffsetDateTime to Milliseconds, I found this way, but I don't know if it is the best one:

book.getInteractionDuration().getStartTimeStamp().toEpochSecond()*1000

Solution

  • I would just convert the OffsetDateTime to an Instant and then use toEpochMilli:

    long millis = book.getInteractionDuration().getStartTimeStamp().toInstant().toEpochMilli();
    

    Unlike toEpochSecond(), this approach won't lose any more precision than is inherent in wanting milliseconds rather than nanoseconds.