A free and open-source video editor for Windows and Linux, written in Rust: a track-based timeline, effects at every level, OpenFX and VST 3 hosts, studio audio and color.
//! Dates of the proleptic Gregorian calendar as days from 1970-01-01.
/// Days from 1970-01-01 to a date of the proleptic Gregorian calendar
/// (Howard Hinnant's algorithm).
pub fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
let y = if month <= 2 { year - 1 } else { year };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let m = month as i64;
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as i64 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
/// The date of a day counted from 1970-01-01: (year, month, day).
pub fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn days_and_dates_go_both_ways() {
assert_eq!(days_from_civil(1970, 1, 1), 0);
assert_eq!(days_from_civil(2000, 3, 1), 11_017);
assert_eq!(civil_from_days(0), (1970, 1, 1));
for d in [-1, 59, 60, 11_016, 11_017, 20_742, 25_000] {
let (y, m, day) = civil_from_days(d);
assert_eq!(days_from_civil(y, m, day), d, "{y}-{m}-{day}");
}
assert_eq!(civil_from_days(20_742), (2026, 10, 16));
}
}