Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OffsetDateTime to milliseconds

Tags:

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
like image 693
Sandro Rey Avatar asked Aug 09 '19 06:08

Sandro Rey


People also ask

What is OffsetDateTime in Java?

OffsetDateTime is an immutable representation of a date-time with an offset. This class stores all date and time fields, to a precision of nanoseconds, as well as the offset from UTC/Greenwich. For example, the value "2nd October 2007 at 13:45.30. 123456789 +02:00" can be stored in an OffsetDateTime .

How do you convert datetime to milliseconds?

A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .

How do I convert datetime to OffsetDateTime?

Converting Date to OffsetDateTimeDate date = new Date(); OffsetDateTime offsetDateTime = date. toInstant() . atOffset(ZoneOffset. UTC);


1 Answers

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.

like image 93
Jon Skeet Avatar answered Sep 17 '22 14:09

Jon Skeet