Search code examples
javazoneddatetime

java zoneddatetime toEpochSecond without converting to local time


I have a dataset that is in EST time without any daylight saving. Each datetime is read from string and a zonedDatetime is created using

ZonedDateTime java.time.ZonedDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone)

with a ZoneId.of("America/New_York");

I need to convert these to an epoch second but the built in toEpochSecond method converts to my local time which is BST with day light saving. As a result the timestamps are four to five hours off depending on time of year. Is there a way to get a unix timestamp that does not take into account any local time so the timestamp matches the datetime in the original string?


Solution

  • To convert ZonedDateTime to Unix epoch time stamp

    Convert first to java.time.Instant and then set zone offset to UTC, before converting it to epoch seconds, see below:

    zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
    

    Note: The variable zonedDateTime is of type java.time.ZonedDateTime and can be in any time zone before converting it to "Unix epoch time stamp" in seconds.