27

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
Sandro Rey
  • 2,429
  • 13
  • 36
  • 80
  • 4
    Do you mean "to milliseconds since the Unix epoch"? I assume so, but I thought it worth checking before answering. – Jon Skeet Aug 09 '19 at 07:03

2 Answers2

39

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    but it gives millis in UTC (I need millis of current time zone) – user924 Nov 26 '19 at 14:04
  • 4
    @user924: Given that the answer was accepted, I don't believe that's what the questioner was looking for. I suggest you ask a new question explaining *why* you believe you want that - it's a pretty unusual requirement, which may have its background in a different problem. – Jon Skeet Nov 26 '19 at 14:40
13

Try this:

long millis = offsetDateTime.toInstant().toEpochMilli();