Skip to content
Advertisement

Compare two dates in years with comma and leap year

There are many entries on the internet how the difference between two dates can be compared. However, I still haven’t found the right solution for me.

In short: I’m looking for the equivalent of dayjs (javascript library – dayJs) function diff with the parameter “years” and a comma. So that I get the output (example): 7.645161290322581 years

const date1 = dayjs('2019-01-25')
date1.diff('2012-06-05', 'year', true) // 6.639424491947131

A nice solution would have been between. Unfortunately, the following code only gives me the year without a comma.

long diff = ChronoUnit.YEARS.between(date1, date2);

Sadly, this solution gives me only 6 years and NOT 6.639424491947131.

I’ve found other solutions, but they don’t take leap years into account.

Could someone please help me here.

//EDIT

Thanks for the anwers. However days is not an option. I need the years with comma. Changed 7.49 to 6.639424491947131

Days / 365 is to inaccurate. Sometimes you have a leap year sometimes not.

Advertisement

Answer

tl;dr

ChronoUnit
.DAYS
.between( 
    LocalDate.parse( "2012-06-05" ) , 
    LocalDate.parse( "2019-01-25" )  
) 
/
365.2425d

See this code run live at IdeOne.com.

6.639424491947131

Details

Why not use a count of days? That is what a decimal fraction of years between dates means: a count of days. A decimal fraction to 15 places creates the illusion of precision that is not actually present when comparing two dates.

LocalDate start = LocalDate.parse( "2012-06-05" ) ;
LocalDate end = LocalDate.parse( "2019-01-25" ) ;

long daysElapsed = ChronoUnit.DAYS.between( start , end ) ;

If you insist on a fraction, divide by whatever fractional count of days per year makes sense to you.

The days per year over a 400 year cycle of the Gregorian calendar is 365.2425.

double DAYS_PER_YEAR = 365.2425d ;
double yearsElapsed = ( daysElapsed / DAYS_PER_YEAR ) ; 

For accuracy, use BigDecimal rather than double.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement