Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting duration to years in Java8 Date API?

I have a date in the far past.
I found out what the duration is between this date and now.
Now I would like to know - how much is this in years?

I came up withthis solution using Java8 API.
This is a monstrous solution, since I have to convert the duration to Days manually first, because there will be an UnsupportedTemporalTypeException otherwise - LocalDate.plus(SECONDS) is not supported for whatever reason.
Even if the compiler allows this call.

Is there a less verbous possibility to convert Duration to years?

LocalDate dateOne = LocalDate.of(1415, Month.JULY, 6);
Duration durationSinceGuss1 = Duration.between(LocalDateTime.of(dateOne, LocalTime.MIDNIGHT),LocalDateTime.now());

long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(), 
        LocalDate.now().plus(
                TimeUnit.SECONDS.toDays(
                        durationSinceGuss1.getSeconds()), 
                ChronoUnit.DAYS) );

/*
 * ERROR - 
 * LocalDate.now().plus(durationSinceGuss1) causes an Exception. 
 * Seconds are not Supported for LocalDate.plus()!!!
 * WHY OR WHY CAN'T JAVA DO WHAT COMPILER ALLOWS ME TO DO?
 */
//long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(), LocalDate.now().plus(durationSinceGuss) );

/*
 * ERROR - 
 * Still an exception! 
 * Even on explicitly converting duration to seconds. 
 * Everything like above. Seconds are just not allowed. Have to convert them manually first e.g. to Days?!
 * WHY OR WHY CAN'T YOU CONVERT SECONDS TO DAYS OR SOMETHING AUTOMATICALLY, JAVA?
 */
//long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(), LocalDate.now().plus(durationSinceGuss.getSeconds(), ChronoUnit.SECONDS) );
like image 994
Skip Avatar asked Sep 13 '25 18:09

Skip


2 Answers

Have you tried using LocalDateTime or DateTime instead of LocalDate? By design, the latter does not support hours/minutes/seconds/etc, hence the UnsupportedTemporalTypeException when you try to add seconds to it.

For example, this works:

LocalDateTime dateOne = LocalDateTime.of(1415, Month.JULY, 6, 0, 0);
Duration durationSinceGuss1 = Duration.between(dateOne, LocalDateTime.now());
long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDateTime.now(), LocalDateTime.now().plus(durationSinceGuss1) );
System.out.println(yearsSinceGuss); // prints 600
like image 162
Matt Ball Avatar answered Sep 16 '25 09:09

Matt Ball


Use Period to get the number of years between two LocalDate objects:

    LocalDate before    = LocalDate.of(1415, Month.JULY, 6);
    LocalDate now       = LocalDate.now();
    Period    period    = Period.between(before, now);

    int yearsPassed     = period.getYears();

    System.out.println(yearsPassed);
like image 23
JVon Avatar answered Sep 16 '25 10:09

JVon