wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
use jiff::Zoned;

/// The decomposed calendar difference between two instants.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Interval {
    pub years: i32,
    pub months: i32,
    pub weeks: i32,
    /// Days excluding whole weeks.
    pub days: i32,
    pub hours: i32,
    pub minutes: i32,
    pub seconds: i32,
    /// True when `from` is after `to` (past direction).
    pub invert: bool,
}

impl Interval {
    /// Components ordered to match the [`Unit`](crate::timediff::Unit) constants.
    #[inline]
    pub(crate) fn values(&self) -> [i32; 7] {
        [
            self.years,
            self.months,
            self.weeks,
            self.days,
            self.hours,
            self.minutes,
            self.seconds,
        ]
    }

    /// Reports whether every component is zero.
    pub fn is_zero(&self) -> bool {
        self.years == 0
            && self.months == 0
            && self.weeks == 0
            && self.days == 0
            && self.hours == 0
            && self.minutes == 0
            && self.seconds == 0
    }
}

/// Days per month, February defaulting to 28 (leap years handled separately).
const DAYS_PER_MONTH: [i32; 13] = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

#[inline]
fn is_leap_year(y: i32) -> bool {
    y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)
}

#[inline]
fn days_in(year: i32, month: i32) -> i32 {
    if month == 2 && is_leap_year(year) {
        29
    } else {
        DAYS_PER_MONTH[month as usize]
    }
}

/// Computes the calendar interval between two instants.
///
/// This replicates PHP `DateInterval`'s behavior: each component comes from
/// calendar arithmetic rather than a total-seconds conversion, so "Jan 1 to
/// Feb 1" is always 1 month regardless of how many days January has. Month-end
/// clipping matches PHP's `diff()` semantics.
///
/// Calendar arithmetic only makes sense within a single zone, so `to` is
/// normalized into `from`'s time zone: comparing fields across zones otherwise
/// skews every component by the offset and can shift the result across day and
/// month boundaries.
pub fn diff(from: &Zoned, to: &Zoned) -> Interval {
    let invert = from > to;
    let (from, to) = if invert { (to, from) } else { (from, to) };
    let to = to.with_time_zone(from.time_zone().clone());

    let (y1, m1, d1) = (from.year() as i32, from.month() as i32, from.day() as i32);
    let (h1, min1, s1) = (
        from.hour() as i32,
        from.minute() as i32,
        from.second() as i32,
    );
    let (mut y2, mut m2, mut d2) = (to.year() as i32, to.month() as i32, to.day() as i32);
    let (h2, min2, s2) = (to.hour() as i32, to.minute() as i32, to.second() as i32);

    // Time components, with borrowing.
    let mut seconds = s2 - s1;
    let mut minutes = min2 - min1;
    let mut hours = h2 - h1;

    if seconds < 0 {
        seconds += 60;
        minutes -= 1;
    }
    if minutes < 0 {
        minutes += 60;
        hours -= 1;
    }
    if hours < 0 {
        hours += 24;
        d2 -= 1; // borrow a day from the date
    }

    // If the day became 0 (or negative), roll back one month.
    if d2 <= 0 {
        m2 -= 1;
        if m2 <= 0 {
            m2 = 12;
            y2 -= 1;
        }
        d2 += days_in(y2, m2);
    }

    // Month/year: total months between the two adjusted dates.
    let mut total_months = (y2 - y1) * 12 + m2 - m1;

    // Day remainder, handling month-boundary clipping.
    let mut days = d2 - d1;
    if days < 0 {
        total_months -= 1;

        let mut prev_m = m2 - 1;
        let mut prev_y = y2;
        if prev_m <= 0 {
            prev_m = 12;
            prev_y -= 1;
        }
        let dim = days_in(prev_y, prev_m);

        // Clip `from`'s day to the max day of that month (PHP behavior).
        let clipped = d1.min(dim);
        days = dim - clipped + d2;
    }

    Interval {
        years: total_months / 12,
        months: total_months % 12,
        weeks: days / 7,
        days: days % 7,
        hours,
        minutes,
        seconds,
        invert,
    }
}