use super::historical;
use crate::core::eph0::{moon_sun_delta_deg, sun_longitude_deg};
use crate::time::jd::JulianDay;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LunarDate {
pub year: i32,
pub month: u32,
pub day: u32,
pub is_leap: bool,
}
impl LunarDate {
pub fn new(year: i32, month: u32, day: u32, is_leap: bool) -> Self {
Self {
year,
month,
day,
is_leap,
}
}
}
const EPOCH_SHUO_JD: f64 = 2451550.257;
const SYNODIC_MONTH: f64 = 29.530588853;
fn find_shuo(jd: f64) -> f64 {
let n = ((jd - EPOCH_SHUO_JD) / SYNODIC_MONTH).round() as i32;
let mut t = EPOCH_SHUO_JD + n as f64 * SYNODIC_MONTH;
for _ in 0..10 {
let d = moon_sun_delta_deg(t);
if d.abs() < 1e-8 {
break;
}
let ep = 0.01;
let der = (moon_sun_delta_deg(t + ep) - moon_sun_delta_deg(t - ep)) / (2.0 * ep);
if der.abs() < 1e-10 {
break;
}
t -= d / der;
}
t
}
fn find_qi(jd_approx: f64, lon: f64) -> f64 {
let mut jd = jd_approx;
for _ in 0..12 {
let l = sun_longitude_deg(jd);
let mut d = l - lon;
d = d.rem_euclid(360.0);
if d > 180.0 {
d -= 360.0;
}
if d.abs() < 1e-6 {
break;
}
jd -= d * 365.25 / 360.0;
}
jd
}
fn index_to_month(idx: usize, leap: Option<usize>, is_leap: bool) -> u32 {
if is_leap {
((idx + 9) % 12 + 1) as u32
} else if let Some(lo) = leap {
if idx > lo {
((idx + 9) % 12 + 1) as u32
} else {
((idx + 10) % 12 + 1) as u32
}
} else {
((idx + 10) % 12 + 1) as u32
}
}
fn month_to_index(
month: u32,
leap: Option<usize>,
is_leap: bool,
lunar_year: i32,
anchor_year: i32,
) -> usize {
let base = ((month + 1) % 12) as usize;
let mut idx = if is_leap {
leap.unwrap_or(base)
} else if let Some(lo) = leap {
if base >= lo { base + 1 } else { base }
} else {
base
};
if idx < 2 && lunar_year > anchor_year {
idx += 12;
}
idx
}
#[allow(clippy::collapsible_if)]
pub fn solar_to_lunar(year: i32, month: u32, day: u32) -> LunarDate {
if year < 1900 {
if let Some(l) = solar_to_lunar_historical(year, month, day) {
return l;
}
}
const UTC8: f64 = 1.0 / 3.0;
for anchor_year in (year - 1).max(1900)..=year.max(1900) {
let dongzhi_jd = find_qi(JulianDay::from_ymd(anchor_year, 12, 1).0, 270.0);
let shuo_idx = ((dongzhi_jd - EPOCH_SHUO_JD) / SYNODIC_MONTH - 1.0).ceil() as i32;
let moons: Vec<(i32, u32, u32)> = (0..15)
.map(|i| {
JulianDay(find_shuo(EPOCH_SHUO_JD + (shuo_idx + i) as f64 * SYNODIC_MONTH) + UTC8)
.to_ymd()
})
.collect();
let (m0_y, m0_m, m0_d) = moons[0];
let jd_m0 = JulianDay::from_ymd(m0_y, m0_m, m0_d).0;
let jd_target = JulianDay::from_ymd(year, month, day).0;
let next_dongzhi_jd = find_qi(dongzhi_jd + 360.0, 270.0);
if jd_target < jd_m0 - 30.0 || jd_target > next_dongzhi_jd + 30.0 {
continue;
}
let leap = if moons.len() > 13 {
(1..moons.len().saturating_sub(1))
.find(|&i| find_mid_qi(&moons[i], &moons[i + 1]).is_none())
} else {
None
};
if let Some((_idx, is_leap, mn, yr, day)) =
locate_in_lunar_context(year, month, day, &moons, leap, anchor_year)
{
return LunarDate::new(yr, mn, day, is_leap);
}
}
LunarDate::new(year, month, day, false)
}
fn find_mid_qi(
start: &(i32, u32, u32), end: &(i32, u32, u32), ) -> Option<usize> {
let start_jd = JulianDay::from_ymd(start.0, start.1, start.2).0;
let end_jd = JulianDay::from_ymd(end.0, end.1, end.2).0;
(0..12).find(|&q| {
let tj = find_qi(start_jd, q as f64 * 30.0);
tj >= start_jd && tj < end_jd
})
}
fn locate_in_lunar_context(
year: i32,
month: u32,
day: u32,
moons: &[(i32, u32, u32)],
leap: Option<usize>,
anchor_year: i32,
) -> Option<(usize, bool, u32, i32, u32)> {
let lunar_year = |idx| {
if idx < 2 {
anchor_year
} else {
anchor_year + 1
}
};
let day_offset = |new_moon: &(i32, u32, u32)| {
days_between(new_moon.0, new_moon.1, new_moon.2, year, month, day) + 1
};
let target = (year, month, day);
for i in 1..moons.len() {
if moons[i] > target {
let idx = i - 1;
let is_leap = leap == Some(idx);
let day = day_offset(&moons[idx]);
let month = index_to_month(idx, leap, is_leap);
return Some((idx, is_leap, month, lunar_year(idx), day));
}
}
if moons.len() >= 2 {
let idx = moons.len() - 2;
let day = day_offset(&moons[idx]);
let month = index_to_month(idx, leap, false);
return Some((idx, false, month, lunar_year(idx), day));
}
None
}
fn solar_to_lunar_historical(year: i32, month: u32, day: u32) -> Option<LunarDate> {
if !(-722..1900).contains(&year) {
return None;
}
for anchor_year in (year - 1)..=year {
if let Some((moons, leap, _era)) = historical::shuo_list(anchor_year) {
let jd_target = JulianDay::from_ymd(year, month, day).0;
let (m0_y, m0_m, m0_d) = moons[0];
let jd_m0 = JulianDay::from_ymd(m0_y, m0_m, m0_d).0;
let (ml_y, ml_m, ml_d) = moons[moons.len() - 1];
let jd_last = JulianDay::from_ymd(ml_y, ml_m, ml_d).0;
if jd_target < jd_m0 - 30.0 || jd_target > jd_last + 30.0 {
continue;
}
if let Some((_idx, is_leap, mn, yr, day)) =
locate_in_lunar_context(year, month, day, &moons, leap, anchor_year)
{
return Some(LunarDate::new(yr, mn, day, is_leap));
}
}
}
None
}
fn days_between(
from_year: i32,
from_month: u32,
from_day: u32,
to_year: i32,
to_month: u32,
to_day: u32,
) -> u32 {
let jd_from = JulianDay::from_ymd(from_year, from_month, from_day).0;
let jd_to = JulianDay::from_ymd(to_year, to_month, to_day).0;
(jd_to - jd_from).round() as u32
}
pub fn lunar_to_solar(lunar: &LunarDate) -> (i32, u32, u32) {
if lunar.month == 0 || lunar.month > 12 || lunar.day == 0 || lunar.day > 30 {
return (lunar.year, lunar.month, lunar.day);
}
const UTC8: f64 = 1.0 / 3.0;
let anchor_year = if lunar.month >= 1 && lunar.month <= 10 {
lunar.year - 1
} else {
lunar.year
};
let dongzhi_jd = find_qi(JulianDay::from_ymd(anchor_year, 12, 1).0, 270.0);
let shuo_idx = ((dongzhi_jd - EPOCH_SHUO_JD) / SYNODIC_MONTH - 1.0).ceil() as i32;
let moons: Vec<(i32, u32, u32)> = (0..15)
.map(|i| {
JulianDay(find_shuo(EPOCH_SHUO_JD + (shuo_idx + i) as f64 * SYNODIC_MONTH) + UTC8)
.to_ymd()
})
.collect();
let leap = if moons.len() > 13 {
(1..moons.len().saturating_sub(1))
.find(|&i| find_mid_qi(&moons[i], &moons[i + 1]).is_none())
} else {
None
};
let idx = month_to_index(lunar.month, leap, lunar.is_leap, lunar.year, anchor_year);
if idx >= moons.len() {
return (lunar.year, lunar.month, lunar.day);
}
let (nm_y, nm_m, nm_d) = moons[idx];
let jd_nm = JulianDay::from_ymd(nm_y, nm_m, nm_d).0;
let target_jd = jd_nm + (lunar.day as f64 - 1.0);
JulianDay(target_jd).to_ymd()
}
pub fn shuo(jd: f64, n: i32) -> f64 {
jd + n as f64 * SYNODIC_MONTH
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_spring_2024() {
let l = solar_to_lunar(2024, 2, 10);
assert!(!l.is_leap);
}
#[test]
fn test_lunar_roundtrip() {
let case = (2024, 2, 10);
let lunar = solar_to_lunar(case.0, case.1, case.2);
assert_eq!(lunar.year, 2024);
assert_eq!(lunar.month, 1);
assert_eq!(lunar.day, 1);
let (ry, rm, rd) = lunar_to_solar(&lunar);
assert_eq!((ry, rm, rd), case);
}
#[test]
fn test_known_dates() {
let cases = [
(2024, 1, 18, 2023, 12, 8, false, "腊八"),
(2024, 2, 10, 2024, 1, 1, false, "春节"),
(2024, 6, 10, 2024, 5, 5, false, "端午"),
(2024, 9, 17, 2024, 8, 15, false, "中秋"),
(2024, 10, 11, 2024, 9, 9, false, "重阳"),
];
for &(y, m, d, ly, lm, ld, ll, lab) in &cases {
let lunar = solar_to_lunar(y, m, d);
assert_eq!(lunar.year, ly, "{}: year", lab);
assert_eq!(lunar.month, lm, "{}: month (xcal={})", lab, lunar.month);
assert_eq!(lunar.day, ld, "{}: day (xcal={})", lab, lunar.day);
assert_eq!(lunar.is_leap, ll, "{}: leap", lab);
}
}
}