Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert LocalDateTime to Instant requires a ZoneOffset. Why?

Tags:

java

java-time

I need to convert a LocalDateTime object to a new Instant object.

I've realized LocalDateTime has an toInstant method, but it's requesting me an ZoneOffset.

I don't quite figure out how to use it, or what does ZoneOffset meant for.

like image 814
Jordi Avatar asked Oct 23 '18 08:10

Jordi


People also ask

What is ZoneOffset?

ZoneOffset extends ZoneId and defines the fixed offset of the current time-zone with GMT/UTC, such as +02:00. This means that this number represents fixed hours and minutes, representing the difference between the time in current time-zone and GMT/UTC: LocalDateTime now = LocalDateTime.

Which class do you use to convert from the local timeline to the instant timeline?

123456789 +02:00 in the Europe/Paris time-zone" can be stored in a ZonedDateTime . This class handles conversion from the local time-line of LocalDateTime to the instant time-line of Instant . The difference between the two time-lines is the offset from UTC/Greenwich, represented by a ZoneOffset .

Does LocalDateTime use UTC?

The LocalDateTime class represents the date-time,often viewed as year-month-day-hour-minute-second and has got no representation of time-zone or offset from UTC/Greenwich.


2 Answers

you can try this:

LocalDateTime dateTime = LocalDateTime.of(2018, Month.OCTOBER, 10, 31, 56);
Instant instant = dateTime.atZone(ZoneId.of("Europe/Rome")).toInstant();
System.out.println(instant);
like image 115
Prima Alessandro Avatar answered Oct 13 '22 06:10

Prima Alessandro


You can't convert a LocalDateTime directly to an Instant because a LocalDateTime can represent many instants. It does not represent one particular instant in time.

Here is a LocalDateTime:

23/10/2018 09:30:00

Can you figure out which instant of time exactly does the above refer to just by looking at it? No. Because that time in the UK is a different instant from that time in China.

To figure out what instant that time refers to, you also need to know how many hours is it offset from UTC, and that, is what ZoneOffset basically represents.

For example, for an offset of 8 hours, you would write this:

localDateTime.toInstant(ZoneOffset.ofHours(8))

Or, if you know you always want the zone offset in the current time zone for that local date time, you can replace ZoneOffset.ofHours(8) with:

ZoneId.systemDefault().getRules().getOffset(localDateTime)

You should think about what offset you want to use before converting it to an instant.

like image 45
Sweeper Avatar answered Oct 13 '22 06:10

Sweeper