Implementation · Rust
Persian (Jalali) calendar in Rust
Dependency-free Rust implementation of the Jalali (Persian, Solar Hijri) calendar: leap years, date validation, Gregorian and Julian Day conversion, weekday and day of year. Verified day by day for 1178–3000 AP. MIT license.
- Requires
- Rust 2024 (1.85+)
- Tested with
- Rust 1.98
- Cross-checked against
- ICU4X 2.4 on every day of the full range (73,048,850 days)
- Language-specific checks
- Full 73M-day sweep in unit test, debug build overflow checks,
clippy - License
- MIT
- Version
- 1.0.0
Quick start
Copy or download the source file into your project (no dependencies).
Optionally, run its tests. The .zip keeps the folder layout they expect; from the language folder:
implementations/rustcargo test --releaseCall the shared API: function reference
Source
src/lib.rs
· 241 lines// Copyright (C) 2026 Goudarz Jafari <hi@goudarzjafari.com>
// SPDX-License-Identifier: MIT
//! Solar Hijri (Persian, Jalali, Shamsi) calendar.
//!
//! Algorithm: 33-year arithmetic rule + 78-year correction table,
//! the same algorithm as ICU 77.1+ and ICU4X (`icu_calendar`). Matches the astronomical calendar
//! (52.5 E meridian) for 1178-3000 AP. Months are 1-based; weekdays 0 = Saturday ... 6 = Friday.
//!
//! For production Rust code prefer `icu_calendar` (ICU4X), which uses the same algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PersianDate {
pub year: i32,
/// 1 = Farvardin ... 12 = Esfand
pub month: u8,
pub day: u8,
}
/// Years checked against the astronomical calendar.
pub const VERIFIED_MIN_YEAR: i32 = 1178;
pub const VERIFIED_MAX_YEAR: i32 = 3000;
/// Accepted input range. Within it every intermediate value fits in 32 bits.
/// Functions return `None` for anything outside it.
pub const MIN_YEAR: i32 = -100_000;
pub const MAX_YEAR: i32 = 100_000;
/// 1 Farvardin -100000 (Gregorian -99379-03-29).
pub const MIN_JDN: i64 = -34_576_287;
/// 29 Esfand 100000 (Gregorian 100622-03-13).
pub const MAX_JDN: i64 = 38_472_562;
const GREGORIAN_MIN_YEAR: i32 = -99_379;
const GREGORIAN_MAX_YEAR: i32 = 100_622;
const EPOCH_JDN: i64 = 1_948_320;
/// Sorted. Years the 33-year rule calls leap but are not; the next year is leap instead.
pub const NON_LEAP_CORRECTION: [i32; 78] = [
1502, 1601, 1634, 1667, 1700, 1733, 1766, 1799, 1832, 1865, 1898, 1931, 1964, 1997, 2030, 2059,
2063, 2096, 2129, 2158, 2162, 2191, 2195, 2224, 2228, 2257, 2261, 2290, 2294, 2323, 2327, 2356,
2360, 2389, 2393, 2422, 2426, 2455, 2459, 2488, 2492, 2521, 2525, 2554, 2558, 2587, 2591, 2620,
2624, 2653, 2657, 2686, 2690, 2719, 2723, 2748, 2752, 2756, 2781, 2785, 2789, 2818, 2822, 2847,
2851, 2855, 2880, 2884, 2888, 2913, 2917, 2921, 2946, 2950, 2954, 2979, 2983, 2987,
];
pub const MONTH_NAMES_FA: [&str; 12] = [
"فروردین",
"اردیبهشت",
"خرداد",
"تیر",
"مرداد",
"شهریور",
"مهر",
"آبان",
"آذر",
"دی",
"بهمن",
"اسفند",
];
pub const MONTH_NAMES_EN: [&str; 12] = [
"Farvardin",
"Ordibehesht",
"Khordad",
"Tir",
"Mordad",
"Shahrivar",
"Mehr",
"Aban",
"Azar",
"Dey",
"Bahman",
"Esfand",
];
pub const WEEKDAY_NAMES_FA: [&str; 7] = [
"شنبه",
"یکشنبه",
"دوشنبه",
"سه\u{200c}شنبه",
"چهارشنبه",
"پنجشنبه",
"جمعه",
];
pub const WEEKDAY_NAMES_EN: [&str; 7] = [
"Saturday",
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
];
fn is_correction(year: i64) -> bool {
i32::try_from(year).is_ok_and(|y| NON_LEAP_CORRECTION.binary_search(&y).is_ok())
}
/// True if the Persian year has 366 days. Total: never panics or overflows for any `i32`
/// (outside `MIN_YEAR..=MAX_YEAR` the answer is the arithmetic extrapolation).
pub fn is_leap_year(year: i32) -> bool {
let year = i64::from(year);
if is_correction(year) {
return false;
}
if is_correction(year - 1) {
return true;
}
(25 * year + 11).rem_euclid(33) < 8
}
/// 29, 30 or 31; `None` if `month` is not 1..=12.
pub fn days_in_month(year: i32, month: u8) -> Option<u8> {
match month {
1..=6 => Some(31),
7..=11 => Some(30),
12 => Some(if is_leap_year(year) { 30 } else { 29 }),
_ => None,
}
}
/// True for a real Persian date in `MIN_YEAR..=MAX_YEAR`.
pub fn is_valid_date(year: i32, month: u8, day: u8) -> bool {
(MIN_YEAR..=MAX_YEAR).contains(&year)
&& days_in_month(year, month).is_some_and(|n| day >= 1 && day <= n)
}
fn nowruz_jdn(year: i64) -> i64 {
let mut jdn = EPOCH_JDN + 365 * (year - 1) + (8 * year + 21).div_euclid(33);
if is_correction(year - 1) {
jdn -= 1;
}
jdn
}
fn days_before_month(month: u8) -> i64 {
let m = i64::from(month);
if m <= 7 {
31 * (m - 1)
} else {
30 * (m - 1) + 6
}
}
/// Julian Day Number of a Persian date; `None` if the date is invalid.
pub fn to_jdn(year: i32, month: u8, day: u8) -> Option<i64> {
is_valid_date(year, month, day)
.then(|| nowruz_jdn(i64::from(year)) + days_before_month(month) + i64::from(day) - 1)
}
/// Persian date of a Julian Day Number; `None` outside `MIN_JDN..=MAX_JDN`.
pub fn from_jdn(jdn: i64) -> Option<PersianDate> {
if !(MIN_JDN..=MAX_JDN).contains(&jdn) {
return None;
}
let mut year = 1 + (33 * (jdn - EPOCH_JDN) + 3).div_euclid(12053);
while jdn >= nowruz_jdn(year + 1) {
year += 1;
}
while jdn < nowruz_jdn(year) {
year -= 1;
}
let doy = jdn - nowruz_jdn(year); // 0-based
let (month, day) = if doy < 186 {
(doy / 31 + 1, doy % 31 + 1)
} else {
((doy - 186) / 30 + 7, (doy - 186) % 30 + 1)
};
Some(PersianDate {
year: year as i32,
month: month as u8,
day: day as u8,
})
}
fn gregorian_days_in_month(year: i32, month: u8) -> u8 {
match month {
2 if year.rem_euclid(4) == 0
&& (year.rem_euclid(100) != 0 || year.rem_euclid(400) == 0) =>
{
29
}
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
/// JDN of a proleptic Gregorian date (month 1..=12); `None` for an invalid date or one
/// outside the accepted range.
pub fn gregorian_to_jdn(year: i32, month: u8, day: u8) -> Option<i64> {
if !(GREGORIAN_MIN_YEAR..=GREGORIAN_MAX_YEAR).contains(&year)
|| !(1..=12).contains(&month)
|| day < 1
|| day > gregorian_days_in_month(year, month)
{
return None;
}
let (month, day) = (i64::from(month), i64::from(day));
let a = (14 - month).div_euclid(12);
let y = i64::from(year) + 4800 - a;
let m = month + 12 * a - 3;
let jdn = day + (153 * m + 2).div_euclid(5) + 365 * y + y.div_euclid(4) - y.div_euclid(100)
+ y.div_euclid(400)
- 32045;
(MIN_JDN..=MAX_JDN).contains(&jdn).then_some(jdn)
}
/// Proleptic Gregorian (year, month, day) of a JDN; `None` outside `MIN_JDN..=MAX_JDN`.
pub fn jdn_to_gregorian(jdn: i64) -> Option<(i32, u8, u8)> {
if !(MIN_JDN..=MAX_JDN).contains(&jdn) {
return None;
}
let a = jdn + 32044;
let b = (4 * a + 3).div_euclid(146097);
let c = a - (146097 * 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 year = 100 * b + d - 4800 + m / 10;
let month = m + 3 - 12 * (m / 10);
let day = e - (153 * m + 2).div_euclid(5) + 1;
Some((year as i32, month as u8, day as u8))
}
pub fn to_gregorian(year: i32, month: u8, day: u8) -> Option<(i32, u8, u8)> {
to_jdn(year, month, day).and_then(jdn_to_gregorian)
}
/// Persian date of a proleptic Gregorian date; `None` for an invalid or out-of-range date.
pub fn from_gregorian(year: i32, month: u8, day: u8) -> Option<PersianDate> {
gregorian_to_jdn(year, month, day).and_then(from_jdn)
}
/// 0 = Saturday (شنبه) ... 6 = Friday (جمعه).
pub fn day_of_week(year: i32, month: u8, day: u8) -> Option<u8> {
to_jdn(year, month, day).map(|jdn| (jdn + 2).rem_euclid(7) as u8)
}
/// 1 ... 365/366.
pub fn day_of_year(year: i32, month: u8, day: u8) -> Option<u16> {
is_valid_date(year, month, day).then(|| (days_before_month(month) + i64::from(day)) as u16)
}Tests
tests/data.rs
262 lines
RustDownload
// Copyright (C) 2026 Goudarz Jafari <hi@goudarzjafari.com>
// SPDX-License-Identifier: MIT
//! Checks the implementation against /data. Run: cargo test --release
use persian_calendar::*;
fn csv(name: &str) -> Vec<Vec<String>> {
let path = format!("{}/../../data/{}", env!("CARGO_MANIFEST_DIR"), name);
let text = std::fs::read_to_string(path).unwrap();
text.trim()
.lines()
.skip(1)
.map(|l| l.split(',').map(String::from).collect())
.collect()
}
fn n<T: std::str::FromStr>(s: &str) -> T
where
T::Err: std::fmt::Debug,
{
s.parse().unwrap()
}
#[test]
fn years() {
for r in csv("years.csv") {
let y: i32 = n(&r[0]);
let leap = r[1] == "1";
assert_eq!(is_leap_year(y), leap, "{y}");
assert_eq!(days_in_month(y, 12), Some(if leap { 30 } else { 29 }));
let (gy, gm, gd) = to_gregorian(y, 1, 1).unwrap();
assert_eq!(format!("{gy:04}-{gm:02}-{gd:02}"), r[3]);
assert_eq!(to_jdn(y, 1, 1), Some(n(&r[4])));
assert_eq!(day_of_week(y, 1, 1), Some(n(&r[5])));
// every day of the year against the ground truth, both directions
let nowruz: i64 = n(&r[4]);
for doy in 0..n::<i64>(&r[2]) {
let (m, d) = if doy < 186 {
(doy / 31 + 1, doy % 31 + 1)
} else {
((doy - 186) / 30 + 7, (doy - 186) % 30 + 1)
};
let (m, d) = (m as u8, d as u8);
let expected = PersianDate {
year: y,
month: m,
day: d,
};
assert_eq!(from_jdn(nowruz + doy), Some(expected));
assert_eq!(to_jdn(y, m, d), Some(nowruz + doy));
}
}
}
#[test]
fn vectors() {
for r in csv("test-vectors.csv") {
let (jy, jm, jd): (i32, u8, u8) = (n(&r[0]), n(&r[1]), n(&r[2]));
let g: (i32, u8, u8) = (n(&r[3]), n(&r[4]), n(&r[5]));
let p = PersianDate {
year: jy,
month: jm,
day: jd,
};
assert_eq!(to_gregorian(jy, jm, jd), Some(g));
assert_eq!(from_gregorian(g.0, g.1, g.2), Some(p));
assert_eq!(to_jdn(jy, jm, jd), Some(n(&r[6])));
assert_eq!(from_jdn(n(&r[6])), Some(p));
assert_eq!(day_of_week(jy, jm, jd), Some(n(&r[7])));
}
}
#[test]
fn every_day_round_trips() {
let first = to_jdn(VERIFIED_MIN_YEAR, 1, 1).unwrap();
let last_day = days_in_month(VERIFIED_MAX_YEAR, 12).unwrap();
let last = to_jdn(VERIFIED_MAX_YEAR, 12, last_day).unwrap();
let mut prev = from_jdn(first - 1).unwrap();
for jdn in first..=last {
let d = from_jdn(jdn).unwrap();
assert_eq!(to_jdn(d.year, d.month, d.day), Some(jdn));
let (gy, gm, gd) = jdn_to_gregorian(jdn).unwrap();
assert_eq!(gregorian_to_jdn(gy, gm, gd), Some(jdn));
let consecutive = (d.day == prev.day + 1 && d.month == prev.month && d.year == prev.year)
|| (d.day == 1
&& ((d.month == prev.month + 1 && d.year == prev.year)
|| (d.month == 1 && prev.month == 12 && d.year == prev.year + 1)));
assert!(consecutive, "{jdn}");
prev = d;
}
}
/// Extrapolated years: years <= 0 make intermediate values negative (floor division matters).
#[test]
fn extrapolated_years() {
assert_eq!(to_jdn(-1000, 1, 1), Some(1_582_713));
assert_eq!(to_jdn(0, 1, 1), Some(1_947_955));
assert_eq!(to_jdn(4000, 1, 1), Some(3_408_925));
assert_eq!(
from_jdn(0),
Some(PersianDate {
year: -5334,
month: 9,
day: 3
})
);
assert_eq!(day_of_week(-1000, 1, 1), Some(1));
assert!(is_leap_year(-3) && !is_leap_year(-1000));
for (first_year, last_year) in [(-1000, 1177), (3001, 4000)] {
let first = to_jdn(first_year, 1, 1).unwrap();
let last = to_jdn(last_year, 12, days_in_month(last_year, 12).unwrap()).unwrap();
let mut prev = from_jdn(first - 1).unwrap();
for jdn in first..=last {
let d = from_jdn(jdn).unwrap();
assert_eq!(to_jdn(d.year, d.month, d.day), Some(jdn));
let (gy, gm, gd) = jdn_to_gregorian(jdn).unwrap();
assert_eq!(gregorian_to_jdn(gy, gm, gd), Some(jdn));
let consecutive =
(d.day == prev.day + 1 && d.month == prev.month && d.year == prev.year)
|| (d.day == 1
&& ((d.month == prev.month + 1 && d.year == prev.year)
|| (d.month == 1 && prev.month == 12 && d.year == prev.year + 1)));
assert!(consecutive, "{jdn}");
prev = d;
}
}
}
#[test]
fn validation_and_known_dates() {
assert!(is_valid_date(1403, 12, 30));
assert!(!is_valid_date(1404, 12, 30));
assert!(is_valid_date(1404, 6, 31));
assert!(!is_valid_date(1404, 7, 31));
assert!(!is_valid_date(1404, 13, 1));
assert!(!is_valid_date(1404, 0, 1));
assert!(!is_valid_date(1404, 1, 0));
assert_eq!(to_jdn(1404, 12, 30), None);
assert_eq!(
from_gregorian(2025, 3, 21),
Some(PersianDate {
year: 1404,
month: 1,
day: 1
})
);
assert_eq!(
from_gregorian(1979, 2, 11),
Some(PersianDate {
year: 1357,
month: 11,
day: 22
})
);
assert_eq!(day_of_year(1404, 7, 1), Some(187));
assert_eq!(
WEEKDAY_NAMES_EN[day_of_week(1404, 1, 1).unwrap() as usize],
"Friday"
);
}
/// Limits: exact boundaries, and `None` for anything outside (no panic, no overflow, no hang).
#[test]
fn limits_and_bad_input() {
assert_eq!(to_jdn(MIN_YEAR, 1, 1), Some(MIN_JDN));
assert_eq!(to_jdn(MAX_YEAR, 12, 29), Some(MAX_JDN));
assert_eq!(
from_jdn(MIN_JDN),
Some(PersianDate {
year: MIN_YEAR,
month: 1,
day: 1
})
);
assert_eq!(
from_jdn(MAX_JDN),
Some(PersianDate {
year: MAX_YEAR,
month: 12,
day: 29
})
);
assert_eq!(jdn_to_gregorian(MIN_JDN), Some((-99379, 3, 29)));
assert_eq!(jdn_to_gregorian(MAX_JDN), Some((100622, 3, 13)));
assert_eq!(gregorian_to_jdn(100622, 3, 13), Some(MAX_JDN));
assert_eq!(gregorian_to_jdn(100622, 3, 14), None);
for bad in [MIN_JDN - 1, MAX_JDN + 1, i64::MAX, i64::MIN, 1 << 53] {
assert_eq!(from_jdn(bad), None, "{bad}");
assert_eq!(jdn_to_gregorian(bad), None, "{bad}");
}
for bad in [MIN_YEAR - 1, MAX_YEAR + 1, i32::MAX, i32::MIN] {
assert!(!is_valid_date(bad, 1, 1));
assert_eq!(to_jdn(bad, 1, 1), None);
let _ = is_leap_year(bad); // total: must not panic
}
for (y, m, d) in [
(2025, 2, 29),
(2025, 2, 30),
(2025, 13, 1),
(2025, 0, 1),
(2025, 4, 31),
(2025, 1, 0),
] {
assert_eq!(gregorian_to_jdn(y, m, d), None, "{y}-{m}-{d}");
assert_eq!(from_gregorian(y, m, d), None, "{y}-{m}-{d}");
}
assert_eq!(
from_gregorian(2024, 2, 29),
Some(PersianDate {
year: 1402,
month: 12,
day: 10
})
);
}
/// Every day of the whole accepted range (73 million days): Persian and Gregorian dates are
/// consecutive, both directions round-trip, and the leap years sit where every other
/// implementation (and ICU 77.1+) puts them (checksums shared by all tests).
#[test]
fn every_day_of_the_full_range() {
let mut prev = from_jdn(MIN_JDN).unwrap();
let mut prev_g = jdn_to_gregorian(MIN_JDN).unwrap();
let (mut leaps, mut nowruz_sum) = (0_i64, MIN_JDN);
for jdn in MIN_JDN + 1..=MAX_JDN {
let d = from_jdn(jdn).unwrap();
if d.month == 1 && d.day == 1 {
nowruz_sum += jdn;
}
if d.month == 12 && d.day == 30 {
leaps += 1;
}
assert_eq!(to_jdn(d.year, d.month, d.day), Some(jdn));
let consecutive = (d.day == prev.day + 1 && d.month == prev.month && d.year == prev.year)
|| (d.day == 1
&& ((d.month == prev.month + 1 && d.year == prev.year)
|| (d.month == 1 && prev.month == 12 && d.year == prev.year + 1)));
assert!(consecutive, "{jdn}");
let g = jdn_to_gregorian(jdn).unwrap();
assert_eq!(gregorian_to_jdn(g.0, g.1, g.2), Some(jdn));
let g_consecutive = (g.2 == prev_g.2 + 1 && g.1 == prev_g.1 && g.0 == prev_g.0)
|| (g.2 == 1
&& ((g.1 == prev_g.1 + 1 && g.0 == prev_g.0)
|| (g.1 == 1 && prev_g.1 == 12 && g.0 == prev_g.0 + 1)));
assert!(g_consecutive, "{jdn}");
prev = d;
prev_g = g;
}
assert_eq!(
prev,
PersianDate {
year: MAX_YEAR,
month: 12,
day: 29
}
);
assert_eq!((leaps, nowruz_sum), (48_485, 389_592_978_180));
assert_eq!(
(MIN_YEAR..=MAX_YEAR).filter(|&y| is_leap_year(y)).count(),
48_485
);
}Project files
Cargo.toml
12 lines
TOMLDownload
[package]
name = "persian-calendar"
version = "1.0.0"
edition = "2024"
rust-version = "1.85"
authors = ["Goudarz Jafari <hi@goudarzjafari.com>"]
description = "Solar Hijri (Persian, Jalali, Shamsi) calendar: conversions, leap years, validation"
license = "MIT"
repository = "https://github.com/Goudarz/PersianCalendar"
publish = false
[dependencies]