use crate::time::jd::JulianDay;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SolarDate {
pub year: i32,
pub month: u32,
pub day: u32,
}
impl SolarDate {
pub fn new(year: i32, month: u32, day: u32) -> Self {
Self { year, month, day }
}
pub fn to_julian_day(&self) -> JulianDay {
JulianDay::from_ymd(self.year, self.month, self.day)
}
pub fn from_julian_day(jd: JulianDay) -> Self {
let (y, m, d) = jd.to_ymd();
Self::new(y, m, d)
}
}
pub fn is_leap_year(year: i32) -> bool {
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}
pub fn days_in_month(year: i32, month: u32) -> u32 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
if is_leap_year(year) {
29
} else {
28
}
}
_ => 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_leap_year() {
assert!(is_leap_year(2000)); assert!(is_leap_year(2024));
assert!(!is_leap_year(1900)); assert!(!is_leap_year(2023));
}
#[test]
fn test_days_in_month() {
assert_eq!(days_in_month(2024, 1), 31);
assert_eq!(days_in_month(2024, 2), 29); assert_eq!(days_in_month(2023, 2), 28); assert_eq!(days_in_month(2024, 4), 30);
assert_eq!(days_in_month(2024, 13), 0); }
#[test]
fn test_solar_date_jd_roundtrip() {
let d = SolarDate::new(2024, 8, 16);
let jd = d.to_julian_day();
let back = SolarDate::from_julian_day(jd);
assert_eq!(d, back);
}
#[test]
fn test_solar_date_epoch() {
let d = SolarDate::new(2000, 1, 1);
let jd = d.to_julian_day();
assert!(jd.0 - 2451545.0 < 0.001, "J2000 JD: {}", jd.0);
}
}