Files
sorsfonalak/crates/astro-engine/src/time.rs
T

73 lines
2.6 KiB
Rust
Raw Normal View History

//! Calendar and Julian Day helpers that do not depend on the ephemeris engine.
/// Julian Day of the Unix epoch (1970-01-01T00:00:00Z).
const UNIX_EPOCH_JD: f64 = 2_440_587.5;
/// Julian Day (UT) for a Unix timestamp given in seconds.
pub fn jd_from_unix_seconds(seconds: f64) -> f64 {
UNIX_EPOCH_JD + seconds / 86_400.0
}
/// Julian Day Number (at noon) of a Julian-calendar date.
pub fn jdn_from_julian_calendar(year: i32, month: u32, day: u32) -> i64 {
let a = (14 - month as i64) / 12;
let y = year as i64 + 4800 - a;
let m = month as i64 + 12 * a - 3;
day as i64 + (153 * m + 2) / 5 + 365 * y + y.div_euclid(4) - 32083
}
/// Proleptic Gregorian calendar date of a Julian Day Number.
pub fn gregorian_from_jdn(jdn: i64) -> (i32, u32, u32) {
let a = jdn + 32044;
let b = (4 * a + 3).div_euclid(146_097);
let c = a - (146_097 * b).div_euclid(4);
let d = (4 * c + 3).div_euclid(1461);
let e = c - (1461 * d).div_euclid(4);
let m = (5 * e + 2).div_euclid(153);
let day = e - (153 * m + 2).div_euclid(5) + 1;
let month = m + 3 - 12 * m.div_euclid(10);
let year = 100 * b + d - 4800 + m.div_euclid(10);
(year as i32, month as u32, day as u32)
}
/// Converts a Julian-calendar date (as recorded e.g. in Russia before 1918)
/// to the proleptic Gregorian date of the same day.
pub fn julian_to_gregorian(year: i32, month: u32, day: u32) -> (i32, u32, u32) {
gregorian_from_jdn(jdn_from_julian_calendar(year, month, day))
}
/// Validates a Julian-calendar date (every 4th year is a leap year).
pub fn is_valid_julian_date(year: i32, month: u32, day: u32) -> bool {
let leap = year.rem_euclid(4) == 0;
let days = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return false,
};
(1..=days).contains(&day)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unix_epoch() {
assert_eq!(jd_from_unix_seconds(0.0), 2_440_587.5);
// J2000.0 = 2000-01-01T12:00:00 = 946728000
assert!((jd_from_unix_seconds(946_728_000.0) - 2_451_545.0).abs() < 1e-9);
}
#[test]
fn julian_calendar_conversion() {
// Russian October Revolution: 25 Oct 1917 (Julian) = 7 Nov 1917 (Gregorian)
assert_eq!(julian_to_gregorian(1917, 10, 25), (1917, 11, 7));
// Last Julian day before the Gregorian reform: 4 Oct 1582 -> 14 Oct 1582
assert_eq!(julian_to_gregorian(1582, 10, 4), (1582, 10, 14));
assert!(is_valid_julian_date(1900, 2, 29));
assert!(!is_valid_julian_date(1901, 2, 29));
}
}