Jordi
Jordi

Reputation: 23237

Convert LocalDateTime to Instant requires a ZoneOffset. Why?

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.

Upvotes: 15

Views: 14503

Answers (2)

Sweeper
Sweeper

Reputation: 271355

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.

Upvotes: 25

Prima Alessandro
Prima Alessandro

Reputation: 178

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);

Upvotes: 4

Related Questions