Skip to main content

Crate date_differencer

Crate date_differencer 

Source
Expand description

§Date Differencer

Calculate the time interval between two supported date-time values and output the result in years plus months plus days plus hours plus minutes plus seconds plus nanoseconds (instead of representing the same duration in different units). This library is useful for lifespan check and age calculation.

§Supported Date-Time Crates

Date-time crate support is enabled through Cargo features. Enable only the providers your project uses.

FeatureTime-zone aware typesNaive/local date-time types
chronochrono::DateTime<Tz>chrono::NaiveDateTime
jiffjiff::Zonedjiff::civil::DateTime
timetime::OffsetDateTime, time::UtcDateTimetime::PrimitiveDateTime

Time-zone aware types keep a timezone or UTC offset in the value. Naive/local types store only calendar and clock fields, so the caller decides how to interpret them.

§Usage

use chrono::prelude::*;

use date_differencer::{add_date_time_diff, date_diff, date_time_diff};

let a = Local.with_ymd_and_hms(2022, 4, 6, 0, 0, 0).unwrap();
let b = Local.with_ymd_and_hms(2023, 6, 9, 1, 0, 0).unwrap();

println!("{:?}", date_diff(a, b));
/*
{
    "years": 1,
    "months": 2,
    "days": 3
}
*/

println!("{:?}", date_time_diff(a, b));
/*
{
    "years": 1,
    "months": 2,
    "days": 3,
    "hours": 1,
    "minutes": 0,
    "seconds": 0,
    "nanoseconds": 0
}
*/

println!("{}", add_date_time_diff(a, &date_time_diff(a, b)).unwrap()); // the same as b

This library can handle leap years and odd/even number of days in a month correctly. The result of following code is a bit confusing but reasonable.

use chrono::prelude::*;

use date_differencer::date_diff;

let a = Local.with_ymd_and_hms(2020, 2, 27, 0, 0, 0).unwrap();
let b = Local.with_ymd_and_hms(2021, 3, 1, 0, 0, 0).unwrap();

println!("{:?}", date_diff(a, b));
/*
{
    "years": 1,
    "months": 0,
    "days": 2
}

Explanation:
    1. 2020-02-27 + 1 year -> 2021-02-27
    2. 2021-02-27 + 2 days -> 2021-03-01 (2021-02 has 28 days)
*/

println!("{:?}", date_diff(b, a));
/*
{
    "years": -1,
    "months": 0,
    "days": -3
}

Explanation:
    1. 2021-03-01 - 1 year -> 2020-03-01
    2. 2020-03-01 - 3 days -> 2020-02-27 (2020-02 has 29 days)
*/

Structs§

DateDiffResult
The result of the date_diff function.
DateTimeDiffResult
The result of the date_time_diff function.

Traits§

AddDateTimeDiff
A trait for date-time types that can apply a DateTimeDiff.
DateTimeDiff
A trait to represent a date-time difference with multiple units.
DateTimeParts
A trait to expose the date and time fields used by this crate.

Functions§

add_date_time_diff
Calculate from + date_time_diff.
date_diff
Calculate the difference between two DateTime instances.
date_time_diff
Calculate the difference between two DateTime instances.