Difference between dates, in years

The difference between Dates.Date returns a Day object. I want to get that number of days “in years”. I’ve been doing stuff like this d/Day(1)/365.25, but repeatedly typing number literals is so ripe for a typo, let alone all the standard time hazards. Is there a better way?

julia> let d = Date(2010, 01, 01) - Date(2000, 01, 01)
           d/Day(1)/365.25
       end
10.001368925393566

You may want to take a look at the DateFormats.jl package. However, the decimal result is slightly different:

using Dates, DateFormats
d1 = Date(2010, 01, 01)
d2 = Date(2000, 01, 01)
yeardecimal(d1 - d2)        # 10.001574296529018

The package may use an average Gregorian year, said to be 365.2425 days

1 Like

What does a difference between dates “in years” mean to you, what is a useful definition for your purposes? Your current method of dividing by 365.25 only makes sense if the interval between the dates has exactly 3:1 ratio of nonleap vs leap years. Otherwise it’s off and is either a little too high or a little too low.

For eg. Date(2008, 01, 01) -ʸ Date(2005, 01, 01) (where I use to mean difference in years) has no leap year in the interval, but any calculation that takes the Day difference first (both your version and rafael’s yeardecimal version) loses that information about leap years and so cannot take that into account.

Another question to help get the precise definition of “difference in years” that makes sense to you: would you expect Date(2008, 12, 31) -ʸ Date(2007, 12, 31) to return 1 year? How about Date(2007, 12, 31) -ʸ Date(2006, 12, 31)? (2008 is a leap year and 2007 is not.)

4 Likes

yeardecimal of date difference fundamentally has to assume some fixed year duration. Most often that’s fine, but there’s also a more well-defined operation:

yeardecimal(d1) - yeardecimal(d2)

Here, each date is converted to the decimal part of that specific year, making the meaning clear and unambiguous.

2 Likes