Using LocalDate, I got the difference expressed in a Period instance. For example:
LocalDate born = LocalDate.of(1990, Month.SEPTEMBER, 30);
Period myAge = Period.between(born, LocalDate.now());
System.out.println("My age is: "+myAge.getYears()+" years "+myAge.getMonths()+" months "+myAge.getDays()+" days.");
Output:
My age is: 26 years 6 months 23 days
So, I was using period to get the age in years, months and days.
I would like to do the same with ZoneDateTime using two time zones (US/Pacific and Australia/Melbourne). For example:
ZonedDateTime now = ZonedDateTime.now(); // US/Pacific
LocalDate date = LocalDate.of(1990, Month.SEPTEMBER, 30);
LocalTime time = LocalTime.of(23, 55);
ZoneId zone = ZoneId.of("Australia/Melbourne");
ZonedDateTime born = ZonedDateTime.of(date, time, zone);
I would like to get the same output as I got with LocalDate. What should I do? Does it make sense?
Expected output:
My age is: 26 years 6 months 24 days
The first line of Period
documentation state that it is a date based amount of time in ISO-8601 format. It is not meant to be used with XXXTime.
However, ZonedDateTime
offer you an until
method which will return the number of a given ChronoUnit
until another Temporal
(now
in your case).
For example :
born.until(now, ChronoUnit.YEARS);
would return 26.
One trick is to add the difference retrieved to the starting date and then process the next ChronoUnit
For example :
long years = born.until(now, ChronoUnit.YEARS);
born = born.plusYears(years);
long months = born.until(now, ChronoUnit.MONTHS);
born = born.plusMonths(months);
long days = born.until(now, ChronoUnit.DAYS);
And then you can print your variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With