Search code examples
javajava-8epochlocaldate

java.time.DateTimeException: Invalid value for Year (valid values -999999999 - 999999999)


I am getting this exception when I am trying to convert epochTime to LocalDate where:

1) Date : 2017-05-05 10:08:52.0

2) corresponding epoch :1493959132000

LocalDate lastUpdatedDate = LocalDate.ofEpochDay(1493959132000);

Exception :

java.time.DateTimeException: Invalid value for Year (valid values -999999999 - 999999999): 4090323145
    at java.time.temporal.ValueRange.checkValidIntValue(ValueRange.java:330)
    at java.time.temporal.ChronoField.checkValidIntValue(ChronoField.java:722)
    at java.time.LocalDate.ofEpochDay(LocalDate.java:341)

I understand that the sourcecode of java.time.LocalDate gives a prior warning of this exception at https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#ofEpochDay-long-

What does this actually mean and when does it come?


Solution

  • Here's javadoc of ofEpochDay, this is what it says:

    This returns a LocalDate with the specified epoch-day. The EPOCH_DAY is a simple incrementing count of days where day 0 is 1970-01-01. Negative numbers represent earlier days.

    So, it expects the argument to be number of days since 1970-01-01. As the value you are passing is not valid, it throws the Exception.

    Now, coming to your use case, if you want to convert epoch time to localdate then you need to use ofEpochMilli method of Instant class, e.g.:

    LocalDate localDate =
            Instant.ofEpochMilli(1493959132000l).atZone(ZoneId.systemDefault()).toLocalDate();
    System.out.println(localDate);
    

    Here's javadoc for Instant class.

    Update

    Alternatively, you can convert the timestamp into number of days since 1970-01-01 and pass it to ofEpochDay() method, e.g.:

    LocalDate localDate = LocalDate.ofEpochDay(1493959132000l/(1000 * 60 *60 * 24));
    System.out.println(localDate);