Back to Blog
2 min read

How to Calculate Age in Rust (chrono and Birthday Logic Examples)

Learn how to calculate age from date of birth in Rust with chrono. Includes completed years, an as-of date example, leap year notes, and copy ready code.

How to Calculate Age in Rust (chrono and Birthday Logic Examples)

If you need to calculate age in Rust, the main goal is usually completed years. That means you cannot just subtract birth year from current year. You also need to check whether the birthday already happened this year.

Quick option: check the result first

If you want to verify the expected output before coding, use the age calculator with a date of birth and an as of date.

Using chrono

In Rust, the most common approach is to work with NaiveDate from chrono and subtract one year if the birthday has not happened yet.

use chrono::{Datelike, NaiveDate};

fn age_in_years(dob: NaiveDate, as_of: NaiveDate) -> i32 {
    let mut age = as_of.year() - dob.year();

    if (as_of.month(), as_of.day()) < (dob.month(), dob.day()) {
        age -= 1;
    }

    age
}

fn main() {
    let dob = NaiveDate::from_ymd_opt(1990, 10, 12).unwrap();
    let as_of = NaiveDate::from_ymd_opt(2026, 3, 30).unwrap();

    println!("{}", age_in_years(dob, as_of));
}

Age as of today

If you want the current age, get today's date and pass it into the same helper.

use chrono::Utc;

let today = Utc::now().date_naive();
let age = age_in_years(dob, today);

Common pitfalls

  • Year minus year only: this overcounts before the birthday.
  • DateTime vs date: for date of birth, a plain date is usually safer than a full timestamp.
  • Leap day birthdays: decide how your app handles Feb 29 in non leap years, then test that rule explicitly.

When exact age matters

If you need years, months, and days, use a dedicated date difference approach and validate the output carefully. For many forms and eligibility checks, completed years are enough.

Related