Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 – Create Instant from LocalDateTime with TimeZone [duplicate]

I have a date stored in the DB in string format ddMMyyyy and hh:mm and the TimeZone. I want to create an Instant based on that information, but I don't know how to do it.

something like

LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 1, 13, 39);
Instant instant = dateTime.toInstant(TimeZone.getTimeZone("ECT"));
like image 848
La Carbonell Avatar asked Jun 15 '17 13:06

La Carbonell


2 Answers

You can first create a ZonedDateTime with that time zone, and then call toInstant:

LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 15, 13, 39);
Instant instant = dateTime.atZone(ZoneId.of("Europe/Paris")).toInstant();
System.out.println(instant); // 2017-06-15T11:39:00Z

I also switched to using the full time zone name (per Basil's advice), since it is less ambiguous.

like image 167
Jorn Vernee Avatar answered Oct 23 '22 00:10

Jorn Vernee


Forget the old TimeZone class. Use ZoneId, because it's properly thread-safe and you can just use a final static field to store the zone.

LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 1, 13, 39);
ZonedDateTime.of(dateTime, ZoneId.of("ECT")).toInstant();
like image 41
coladict Avatar answered Oct 23 '22 02:10

coladict