use jiff::civil::Date;
use jiff::{SignedDuration, Timestamp};
use std::f64::consts::PI;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Daylight {
Normal { rise: Timestamp, set: Timestamp },
AlwaysUp,
AlwaysDown,
}
pub fn daylight(date: Date, lat: f64, lon: f64) -> Daylight {
let day = f64::from(date.day_of_year());
let days_in_year = if date.in_leap_year() { 366.0 } else { 365.0 };
let g = 2.0 * PI / days_in_year * (day - 1.0);
let eqtime = 229.18
* (0.000075 + 0.001868 * g.cos()
- 0.032077 * g.sin()
- 0.014615 * (2.0 * g).cos()
- 0.040849 * (2.0 * g).sin());
let decl = 0.006918 - 0.399912 * g.cos() + 0.070257 * g.sin() - 0.006758 * (2.0 * g).cos()
+ 0.000907 * (2.0 * g).sin()
- 0.002697 * (3.0 * g).cos()
+ 0.00148 * (3.0 * g).sin();
let phi = lat.to_radians();
let cos_ha = 90.833f64.to_radians().cos() / (phi.cos() * decl.cos()) - phi.tan() * decl.tan();
if cos_ha > 1.0 {
return Daylight::AlwaysDown;
}
if cos_ha < -1.0 {
return Daylight::AlwaysUp;
}
let ha = cos_ha.acos().to_degrees();
let rise = 720.0 - 4.0 * (lon + ha) - eqtime;
let set = 720.0 - 4.0 * (lon - ha) - eqtime;
let midnight = date
.to_zoned_datetime(jiff::tz::TimeZone::UTC)
.expect("a valid date")
.timestamp();
let at = |minutes: f64| midnight + SignedDuration::from_secs((minutes * 60.0).round() as i64);
Daylight::Normal {
rise: at(rise),
set: at(set),
}
}
pub fn is_day(date: Date, lat: f64, lon: f64, now: Timestamp) -> bool {
match daylight(date, lat, lon) {
Daylight::Normal { rise, set } => rise <= now && now < set,
Daylight::AlwaysUp => true,
Daylight::AlwaysDown => false,
}
}
pub fn parse_location(text: &str) -> Option<(f64, f64)> {
let mut parts = text.split([',', ';', ' ']).filter(|p| !p.is_empty());
let lat: f64 = parts.next()?.trim().parse().ok()?;
let lon: f64 = parts.next()?.trim().parse().ok()?;
if parts.next().is_some() || !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon)
{
return None;
}
Some((lat, lon))
}
#[cfg(test)]
mod tests {
use super::*;
use jiff::civil::date;
use jiff::tz::TimeZone;
fn local_minutes(t: Timestamp, tz: &str) -> i64 {
let z = t.to_zoned_datetime(TimeZone::get(tz).unwrap());
i64::from(z.hour()) * 60 + i64::from(z.minute())
}
fn assert_near(got: i64, want: (i64, i64), what: &str) {
let want = want.0 * 60 + want.1;
assert!(
(got - want).abs() <= 3,
"{what}: {}:{:02}",
got / 60,
got % 60
);
}
#[test]
fn new_york_at_midsummer() {
let Daylight::Normal { rise, set } = daylight(date(2026, 6, 21), 40.7128, -74.0060) else {
panic!("the sun rises in New York");
};
assert_near(local_minutes(rise, "America/New_York"), (5, 25), "sunrise");
assert_near(local_minutes(set, "America/New_York"), (20, 31), "sunset");
}
#[test]
fn london_at_midwinter() {
let Daylight::Normal { rise, set } = daylight(date(2026, 12, 21), 51.5074, -0.1278) else {
panic!("the sun rises in London");
};
assert_near(local_minutes(rise, "Europe/London"), (8, 4), "sunrise");
assert_near(local_minutes(set, "Europe/London"), (15, 53), "sunset");
}
#[test]
fn tokyo_sunrise_falls_on_the_utc_day_before() {
let Daylight::Normal { rise, set } = daylight(date(2026, 6, 21), 35.6762, 139.6503) else {
panic!("the sun rises in Tokyo");
};
assert_near(local_minutes(rise, "Asia/Tokyo"), (4, 25), "sunrise");
assert_near(local_minutes(set, "Asia/Tokyo"), (19, 0), "sunset");
assert!(rise < set);
}
#[test]
fn polar_day_and_night() {
assert_eq!(
daylight(date(2026, 6, 21), 69.65, 18.96),
Daylight::AlwaysUp
);
assert_eq!(
daylight(date(2026, 12, 21), 69.65, 18.96),
Daylight::AlwaysDown
);
}
#[test]
fn day_and_night_at_a_place() {
let at = |h: i8, m: i8| {
date(2026, 6, 21)
.at(h, m, 0, 0)
.to_zoned_datetime(TimeZone::get("America/New_York").unwrap())
.unwrap()
.timestamp()
};
let d = date(2026, 6, 21);
assert!(!is_day(d, 40.7128, -74.0060, at(5, 0)));
assert!(is_day(d, 40.7128, -74.0060, at(12, 0)));
assert!(is_day(d, 40.7128, -74.0060, at(20, 20)));
assert!(!is_day(d, 40.7128, -74.0060, at(21, 0)));
}
#[test]
fn locations_parse() {
assert_eq!(parse_location("40.71, -74.01"), Some((40.71, -74.01)));
assert_eq!(parse_location(" -33.87;151.21 "), Some((-33.87, 151.21)));
assert_eq!(parse_location("51.5 -0.13"), Some((51.5, -0.13)));
assert_eq!(parse_location("91, 0"), None);
assert_eq!(parse_location("40.71"), None);
assert_eq!(parse_location("north, west"), None);
assert_eq!(parse_location("1, 2, 3"), None);
}
}