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.
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.
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 .
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With