Search code examples
javalocaldatejava-time

Get correct temporal type from passed object


Is there a way to determine the temporal type of a passed object? Currently I have a Temporal parameter that turns a Temporal into a LocalDate and returns the LocalDate object.

Assuming I pass a LocalDateTime in this Temporal parameter, the method will raise an exception.

Is there a way to find out the type of the passed temporal?


Solution

  • I don’t know how you made your conversion to LocalDate. I believe that this one works.

    /**
     * @throws DateTimeException if the <code>Temporal</code> hasn’t got
     * enough supported fields for a <code>LocalDate</code>.
     */
    public static LocalDate convertToLocalDate(Temporal t) {
        return LocalDate.from(t);
    }
    

    It has no problem accepting a LocalDateTime:

        LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Qyzylorda"));
        System.out.println("As LocalDate: " + convertToLocalDate(ldt));
    

    When I ran this code just now, I got this output:

    As LocalDate: 2020-03-13
    

    It doesn’t work for just any Temporal at all, of course.

        convertToLocalDate(Year.of(2021));
    
    Exception in thread "main" java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: 2021 of type java.time.Year
      at java.base/java.time.LocalDate.from(LocalDate.java:396)
      at com.ajax.Demo.convertToLocalDate(ConvertTemporalToLocalDate.java:18)
      at com.ajax.Demo.main(ConvertTemporalToLocalDate.java:25)