Customizing Output Units of Dates.canonicalize

Working on some exercises to learn programming and Julia, and I am attempting to calculate my little one’s age.

I see that Julia does almost all of the work compared to the solution I wrote yesterday in Perl where I had to do most of it manually, wanting to use only built-in functions (adding no modules).

What I would like to add to my Julia solution is an age output in “x months, y days” or some variation of “x months” and other smaller units.

Canonicalize already gives me “x weeks, y days” but I don’t see a way to tell Dates.canonicalize which units I want. It seems to decide for itself based on the documentation.

Note that my time duration is coming from Julia performing algebra on two dates.

Is there any way to request specific units from Dates.canonicalize?


julia> birthday = Dates.Date(2022,9,7)

julia> today_date =

julia> age = today_date - birthday
74 days

julia> Dates.canonicalize(age)
10 weeks, 4 days
help?> Dates.canonicalize
  canonicalize(::CompoundPeriod) -> CompoundPeriod

  Reduces the CompoundPeriod into its canonical form by applying the following rules:

    •  Any Period large enough be partially representable by a coarser Period will be broken into multiple Periods (eg. Hour(30)
       becomes Day(1) + Hour(6))

canonicalize does what it does, there are no options.
In your example, there is no good way to determine say, Months and Days from the total number of days because the number of days per month varies.

Here is a small hackish solution for calculating number of months and days since the birthday assuming that one month is calculated from birth date till the same date in the next month:

function calculate_months(start_date::Date, end_date::Date)
    months = Month(0)
    date = start_date + Month(1)
    while(date <= end_date)
        date += Month(1)
        months += Month(1)
    days = end_date - (start_date + months)
    print(months, ' ', days)
julia> calculate_months(birthday, today())
2 months 14 days
1 Like

Thanks, it certainly seemed that way, but since I just started out reading programming documentation in general I wanted to make sure I wasn’t missing something. :+1:

Thank you for the code. It seems to do just what I was looking to do, and is brief thanks to the way the month type works. I will test it out! :star: