How to extract epoch from LocalDate and LocalDateTime?

user1019830 picture user1019830 · Apr 10, 2014 · Viewed 116k times · Source

How do I extract the epoch value to Long from instances of LocalDateTime or LocalDate? I've tried the following, but it gives me other results:

LocalDateTime time = LocalDateTime.parse("04.02.2014  19:51:01", DateTimeFormatter.ofPattern("dd.MM.yyyy  HH:mm:ss"));
System.out.println(time.getLong(ChronoField.SECOND_OF_DAY)); // gives 71461
System.out.println(time.getLong(ChronoField.EPOCH_DAY)); // gives 16105

What I want is simply the value 1391539861 for the local datetime "04.02.2014 19:51:01". My timezone is Europe/Oslo UTC+1 with daylight saving time.

Answer

nosid picture nosid · Apr 10, 2014

The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance.

LocalDate

LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();

LocalDateTime

LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();