Rust Hijri
Hijri (Islamic) calendar dates for Rust, built on Jiff. Convert any Jiff date to Hijri and back, add days, months and years in the Hijri calendar, format dates with Arabic or English month names, and parse Hijri strings. It is the Rust port of the PHP Hijri package: the same Gregorian date gives the same Hijri date in both.
Gregorian to Hijri
Convert a Jiff Date, DateTime or ZonedDateTime with one call.
Hijri to Gregorian
Get a Jiff civil date back from any Hijri date.
Hijri Date Math
Add days, months and years, and count the whole months and years between two dates.
Formatting
Format with strftime-style directives such as day, month name and year.
Arabic and English Months
Every month name in Arabic, or transliterated into English.
Same Results as PHP Hijri
The same tabular calendar and the same default adjustment, checked against the PHP package.
A Jiff Timestamp, such as a database created_at, is an instant without a date. Read it in a time zone first, created_at.to_zoned_datetime(tz), then convert it: the same instant can be a different day in Cairo and in UTC.
#Installation
Add the crate to your project with Cargo.
#Requirements
- Rust 1.98 or newer (the crate's
rust-version) - Jiff 1.x, whose dates the crate converts
#Cargo Installation
cargo add pharaonic-hijri jiffOr add the dependencies to Cargo.toml yourself:
1[dependencies]2jiff = "1"3pharaonic-hijri = "1"#Optional Features
The crate has one optional feature, serde, which serializes a HijriDate as its YYYY-MM-DD string. It is off by default:
cargo add pharaonic-hijri --features serdeSee Cargo Features for details.
You're all set! There is nothing to configure: import HijriDate from pharaonic_hijri and start converting dates.
#Basic Usage
HijriDate is a plain value: a Hijri year, month and day. Create one from a Jiff date, read its parts, do date math, format it, and turn it back into a Jiff date.
1use jiff::civil::date; 2use pharaonic_hijri::{Error, HijriDate, Language}; 3 4fn main() -> Result<(), Error> { 5 // Gregorian to Hijri. 6 let ramadan = HijriDate::from_gregorian(date(2024, 3, 11))?; 7 8 assert_eq!(ramadan.to_string(), "1445-09-01"); 9 assert_eq!((ramadan.year(), ramadan.month(), ramadan.day()), (1445, 9, 1));10 assert_eq!(ramadan.month_name(Language::English), "Ramadan");11 12 // Hijri date math.13 let eid = ramadan.checked_add_months(1)?;14 15 assert_eq!(eid.to_string(), "1445-10-01");16 17 // Hijri to Gregorian.18 assert_eq!(eid.to_gregorian()?, date(2024, 4, 10));19 20 // Formatting.21 assert_eq!(eid.strftime("%-d %B %Y", Language::Arabic)?, "1 شوّال 1445");22 23 Ok(())24}Every conversion uses the default adjustment of one day back, the same as the PHP package. Day Adjustment explains it and how to use another one.
HijriDate is Copy, and it implements Eq, Ord and Hash: compare dates with < and ==, sort them, or use them as map keys.
#Day Adjustment
The crate uses the tabular Hijri calendar: a fixed rule for month lengths and leap years. The calendar announced in your country, from moon sighting or from a published calendar such as Umm al-Qura, can differ from it by a day or two. The adjustment moves the Gregorian date by a number of days before it is read as a Hijri date, and back again the other way.
The default is -1 (Converter::DEFAULT_ADJUSTMENT), the same as the PHP package. HijriDate::from_gregorian and HijriDate::to_gregorian always use it.
#Another Adjustment
Use a Converter for any other number of days:
1use jiff::civil::date; 2use pharaonic_hijri::{Converter, Error, HijriDate}; 3 4fn main() -> Result<(), Error> { 5 let today = date(2024, 3, 11); 6 7 assert_eq!(HijriDate::from_gregorian(today)?.to_string(), "1445-09-01"); // -1 8 assert_eq!(Converter::new(0).to_hijri(today)?.to_string(), "1445-09-02"); 9 assert_eq!(Converter::new(1).to_hijri(today)?.to_string(), "1445-09-03");10 11 // The same converter turns its Hijri dates back into the same Gregorian ones.12 let converter = Converter::new(0);13 let hijri = converter.to_hijri(today)?;14 15 assert_eq!(converter.to_gregorian(hijri)?, today);16 17 Ok(())18}#Keeping One Adjustment for Your App
There is no global setting. A Converter is a small Copy value, so build it once from your configuration and pass it where you convert dates:
1use jiff::civil::date; 2use pharaonic_hijri::{Converter, Error, HijriDate}; 3 4struct Settings { 5 hijri: Converter, 6} 7 8fn ramadan_start(settings: &Settings, year: i16) -> Result<jiff::civil::Date, Error> { 9 settings.hijri.to_gregorian(HijriDate::new(year, 9, 1)?)10}11 12fn main() -> Result<(), Error> {13 let settings = Settings { hijri: Converter::new(0) };14 15 assert_eq!(ramadan_start(&settings, 1445)?, date(2024, 3, 10));16 17 Ok(())18}The PHP package has used one day back since its first release, so the Rust crate keeps it: both libraries give the same Hijri date for the same day. Pass Converter::new(0) for the plain tabular calendar.
#Gregorian to Hijri
HijriDate::from_gregorian accepts any Jiff value that has a date: a civil::Date, a civil::DateTime, or a ZonedDateTime, which is read in its own time zone. A Converter has the same input in to_hijri.
1use jiff::civil::date; 2use jiff::ZonedDateTime; 3use pharaonic_hijri::HijriDate; 4 5fn main() -> Result<(), Box<dyn std::error::Error>> { 6 let expected = HijriDate::new(1445, 9, 1)?; 7 8 // A date. 9 assert_eq!(HijriDate::from_gregorian(date(2024, 3, 11))?, expected);10 11 // A date and time: the time doesn't change the day.12 assert_eq!(HijriDate::from_gregorian(date(2024, 3, 11).at(23, 59, 0, 0))?, expected);13 14 // A zoned date and time, read in its own time zone.15 let zoned: ZonedDateTime = "2024-03-11T08:00[Asia/Riyadh]".parse()?;16 17 assert_eq!(HijriDate::from_gregorian(zoned)?, expected);18 19 Ok(())20}#Timestamps and created_at
A jiff::Timestamp is an instant, the same everywhere in the world, so it has no date until you pick a time zone. That's why from_gregorian doesn't accept one: the compiler asks you to choose. Read it in the time zone your users live in:
1use jiff::tz::TimeZone; 2use jiff::Timestamp; 3use pharaonic_hijri::HijriDate; 4 5fn main() -> Result<(), Box<dyn std::error::Error>> { 6 // 22:30 UTC on March 10 is already March 11 in Cairo. 7 let created_at: Timestamp = "2024-03-10T22:30:00Z".parse()?; 8 9 let in_utc = HijriDate::from_gregorian(created_at.to_zoned_datetime(TimeZone::UTC))?;10 let in_cairo = HijriDate::from_gregorian(created_at.to_zoned_datetime(TimeZone::get("Africa/Cairo")?))?;11 12 assert_eq!(in_utc.to_string(), "1445-08-29");13 assert_eq!(in_cairo.to_string(), "1445-09-01");14 15 Ok(())16}#Range
Hijri dates start on 1 Muharram 1 AH, July 19, 622 with the default adjustment. An earlier Gregorian date returns Error::OutOfRange.
1use jiff::civil::date;2use pharaonic_hijri::{Error, HijriDate};3 4fn main() {5 assert_eq!(HijriDate::from_gregorian(date(622, 7, 19)), Ok(HijriDate::MIN));6 assert_eq!(HijriDate::from_gregorian(date(600, 1, 1)), Err(Error::OutOfRange));7}#Hijri to Gregorian
Build a HijriDate from its parts with HijriDate::new, or parse it from a string, then call to_gregorian for a Jiff civil::Date.
1use jiff::civil::date; 2use pharaonic_hijri::{Error, HijriDate}; 3 4fn main() -> Result<(), Error> { 5 let eid = HijriDate::new(1445, 10, 1)?; 6 7 assert_eq!(eid.to_gregorian()?, date(2024, 4, 10)); 8 9 let parsed: HijriDate = "1413-08-08".parse()?;10 11 assert_eq!(parsed.to_gregorian()?, date(1993, 2, 1));12 13 Ok(())14}#Creating Dates
HijriDate::new(year, month, day) checks the date exists. Odd months have 30 days, even months 29, and Dhu Al-Hijjah (month 12) has 30 days in leap years.
1use pharaonic_hijri::{Error, HijriDate};2 3fn main() {4 assert!(HijriDate::new(1445, 1, 30).is_ok());5 assert_eq!(HijriDate::new(1445, 2, 30), Err(Error::InvalidDate)); // Safar 1445 has 29 days6 assert_eq!(HijriDate::new(1445, 13, 1), Err(Error::InvalidDate));7 assert_eq!(HijriDate::new(0, 1, 1), Err(Error::OutOfRange)); // years 1 to 99998}#Parsing Strings
HijriDate implements FromStr for YYYY-MM-DD strings. Single-digit months and days, and surrounding whitespace, are accepted:
1use pharaonic_hijri::{Error, HijriDate};2 3fn main() {4 assert_eq!("1445-09-01".parse::<HijriDate>(), HijriDate::new(1445, 9, 1));5 assert_eq!(" 1445-9-1 ".parse::<HijriDate>(), HijriDate::new(1445, 9, 1));6 assert_eq!("1445/09/01".parse::<HijriDate>(), Err(Error::Parse));7 assert_eq!("1445-02-30".parse::<HijriDate>(), Err(Error::InvalidDate));8}#Adding a Time
The crate works with dates. Add the time on the Gregorian side with Jiff:
1use jiff::civil::date; 2use pharaonic_hijri::HijriDate; 3 4fn main() -> Result<(), Box<dyn std::error::Error>> { 5 let iftar = "1445-09-01".parse::<HijriDate>()?.to_gregorian()?.at(18, 5, 0, 0); 6 7 assert_eq!(iftar, date(2024, 3, 11).at(18, 5, 0, 0)); 8 9 Ok(())10}Jiff dates end on December 31, 9999. A Hijri date that falls after it, from about 9666 AH, returns Error::OutOfRange from to_gregorian.
#Date Math
Arithmetic happens in the Hijri calendar and returns a new date. Each method returns Error::OutOfRange instead of panicking when the result would leave the supported range.
#Adding Days, Months and Years
1use pharaonic_hijri::{Error, HijriDate}; 2 3fn main() -> Result<(), Error> { 4 let date = HijriDate::new(1445, 2, 29)?; 5 6 assert_eq!(date.checked_add_days(1)?.to_string(), "1445-03-01"); 7 assert_eq!(date.checked_add_days(-29)?.to_string(), "1445-01-30"); 8 assert_eq!(date.checked_add_months(1)?.to_string(), "1445-03-29"); 9 assert_eq!(date.checked_add_years(-1)?.to_string(), "1444-02-29");10 11 Ok(())12}Pass a negative number to go back.
#The End of the Month
When the target month is shorter than the day, the result is the last day of that month instead of spilling into the next one. Jiff adds Gregorian months the same way.
1use pharaonic_hijri::{Error, HijriDate}; 2 3fn main() -> Result<(), Error> { 4 // Muharram has 30 days, Safar 29. 5 assert_eq!(HijriDate::new(1445, 1, 30)?.checked_add_months(1)?.to_string(), "1445-02-29"); 6 7 // 1445 is a leap year: Dhu Al-Hijjah 1445 has 30 days, 1446 has 29. 8 assert_eq!(HijriDate::new(1445, 12, 30)?.checked_add_years(1)?.to_string(), "1446-12-29"); 9 10 Ok(())11}#Differences
days_until, months_until and years_until count from the date to another one, negative when the other date is earlier. Months and years are whole: a month counts once adding it doesn't pass the other date.
1use pharaonic_hijri::{Error, HijriDate}; 2 3fn main() -> Result<(), Error> { 4 let start = HijriDate::new(1445, 9, 1)?; 5 let eid = HijriDate::new(1445, 10, 1)?; 6 7 assert_eq!(start.days_until(eid), 30); 8 assert_eq!(start.months_until(eid), 1); 9 assert_eq!(start.months_until(HijriDate::new(1445, 9, 30)?), 0);10 assert_eq!(eid.days_until(start), -30);11 12 // An age in Hijri years.13 let born = HijriDate::new(1410, 6, 4)?;14 15 assert_eq!(born.years_until(HijriDate::new(1448, 6, 3)?), 37);16 assert_eq!(born.years_until(HijriDate::new(1448, 6, 4)?), 38);17 18 Ok(())19}#Comparing Dates
Dates compare and sort chronologically. To compare a Hijri date with a Gregorian one, convert one side first:
1use jiff::civil::date; 2use pharaonic_hijri::{Error, HijriDate}; 3 4fn main() -> Result<(), Error> { 5 let ramadan = HijriDate::new(1445, 9, 1)?; 6 let today = HijriDate::from_gregorian(date(2024, 3, 20))?; 7 8 assert!(today > ramadan); 9 assert!(today < ramadan.checked_add_months(1)?);10 11 Ok(())12}#Formatting
#Display
A HijriDate prints as YYYY-MM-DD, with the year padded to four digits. Parsing that string gives the same date back.
1use pharaonic_hijri::{Error, HijriDate}; 2 3fn main() -> Result<(), Error> { 4 let date = HijriDate::new(1445, 9, 1)?; 5 6 assert_eq!(date.to_string(), "1445-09-01"); 7 assert_eq!(format!("Ramadan starts on {date}"), "Ramadan starts on 1445-09-01"); 8 assert_eq!(date.to_string().parse::<HijriDate>()?, date); 9 10 Ok(())11}#strftime
strftime formats with these directives. The month name follows the Language you pass.
| Directive | Output | Example |
|---|---|---|
%Y | Year, at least four digits | 1445 |
%y | Last two digits of the year | 45 |
%m | Month, two digits | 09 |
%-m | Month, no padding | 9 |
%d | Day, two digits | 05 |
%-d | Day, no padding | 5 |
%e | Day, padded with a space | 5 |
%j | Day of the year, three digits | 241 |
%B | Month name | Ramadan, رَمضان |
%% | A literal % | % |
1use pharaonic_hijri::{Error, HijriDate, Language}; 2 3fn main() -> Result<(), Error> { 4 let date = HijriDate::new(1445, 9, 5)?; 5 6 assert_eq!(date.strftime("%-d %B %Y", Language::English)?, "5 Ramadan 1445"); 7 assert_eq!(date.strftime("%d %B %Y هـ", Language::Arabic)?, "05 رَمضان 1445 هـ"); 8 assert_eq!(date.strftime("%Y/%m/%d", Language::English)?, "1445/09/05"); 9 10 // Any other directive is an error, never silently dropped.11 assert_eq!(date.strftime("%A", Language::English), Err(Error::UnknownDirective));12 13 Ok(())14}#Weekdays and Times
The weekday and the time belong to the Gregorian date, so format them with Jiff and join the two:
1use jiff::civil::date; 2use pharaonic_hijri::{HijriDate, Language}; 3 4fn main() -> Result<(), Box<dyn std::error::Error>> { 5 let day = date(2024, 3, 11); 6 let hijri = HijriDate::from_gregorian(day)?; 7 8 let label = format!("{}, {}", day.strftime("%A"), hijri.strftime("%-d %B %Y", Language::English)?); 9 10 assert_eq!(label, "Monday, 1 Ramadan 1445");11 12 Ok(())13}#Month Names
month_name returns the month's name in a Language:
| Month | Arabic | English |
|---|---|---|
| 1 | مُحرَّم | Muharram |
| 2 | صفَر | Safar |
| 3 | ربيع الأول | Rabi' Al-Awwal |
| 4 | ربيع الآخر | Rabi' Al-Akher |
| 5 | جمادى الأول | Jumada Al-Awwal |
| 6 | جمادى الآخرة | Jumada Al-Akherah |
| 7 | رَجب | Rajab |
| 8 | شَعبان | Sha'aban |
| 9 | رَمضان | Ramadan |
| 10 | شوّال | Shawwal |
| 11 | ذو القِعدة | Dhu Al-Qi'dah |
| 12 | ذو الحِجّة | Dhu Al-Hijjah |
1use pharaonic_hijri::{Error, HijriDate, Language}; 2 3fn main() -> Result<(), Error> { 4 let date = HijriDate::new(1445, 12, 10)?; 5 6 assert_eq!(date.month_name(Language::Arabic), "ذو الحِجّة"); 7 assert_eq!(date.month_name(Language::English), "Dhu Al-Hijjah"); 8 9 Ok(())10}#Hijri Calendar
The crate uses the tabular Hijri calendar, the same one as the PHP package:
- Odd months have 30 days and even months 29.
- Dhu Al-Hijjah (month 12) has 30 days in leap years, so a leap year has 355 days and a common year 354.
- Leap years are years 2, 5, 7, 10, 13, 15, 18, 21, 24, 26 and 29 of each 30-year cycle.
Each HijriDate answers these for its own year and month:
1use pharaonic_hijri::{Error, HijriDate}; 2 3fn main() -> Result<(), Error> { 4 let date = HijriDate::new(1445, 9, 11)?; 5 6 assert!(date.is_leap_year()); 7 assert_eq!(date.days_in_year(), 355); 8 assert_eq!(date.days_in_month(), 30); 9 assert_eq!(date.day_of_year(), 247);10 11 assert!(!HijriDate::new(1446, 1, 1)?.is_leap_year());12 13 Ok(())14}#Supported Range
| Constant | Date |
|---|---|
HijriDate::MIN | 1 Muharram 1 AH (0001-01-01) |
HijriDate::MAX | 29 Dhu Al-Hijjah 9999 AH (9999-12-29) |
Conversions to Gregorian are limited by Jiff's last date, December 31, 9999, which is about 9666 AH.
#Cargo Features
| Feature | Default | Enables |
|---|---|---|
serde | off | Serialize and Deserialize for HijriDate |
#serde
With serde, a HijriDate is serialized as its YYYY-MM-DD string, and deserializing checks the date like HijriDate::new does.
1[dependencies]2pharaonic-hijri = { version = "1", features = ["serde"] }3serde = { version = "1", features = ["derive"] }4serde_json = "1" 1use pharaonic_hijri::HijriDate; 2use serde::{Deserialize, Serialize}; 3 4#[derive(Debug, Serialize, Deserialize)] 5struct Event { 6 name: String, 7 date: HijriDate, 8} 9 10fn main() -> Result<(), Box<dyn std::error::Error>> {11 let event = Event { name: "Eid al-Fitr".into(), date: HijriDate::new(1445, 10, 1)? };12 13 assert_eq!(serde_json::to_string(&event)?, r#"{"name":"Eid al-Fitr","date":"1445-10-01"}"#);14 15 let invalid = serde_json::from_str::<Event>(r#"{"name":"x","date":"1445-02-30"}"#);16 17 assert!(invalid.unwrap_err().to_string().contains("invalid hijri date"));18 19 Ok(())20}#Errors
Every fallible method returns Result<_, pharaonic_hijri::Error>. The crate never panics on your input. Error implements std::error::Error, so ? turns it into Box<dyn Error>, anyhow::Error and similar types.
| Variant | When | Message |
|---|---|---|
Error::InvalidDate | The month or the day doesn't exist (1445-02-30, month 13) | invalid hijri date |
Error::OutOfRange | A year outside 1 to 9999, a Gregorian date before July 622 or after the end of Jiff's dates, or math that leaves that range | date is outside the supported range |
Error::Parse | A string that isn't YYYY-MM-DD | hijri date must use the YYYY-MM-DD format |
Error::UnknownDirective | A strftime directive the crate doesn't support, or a % at the end | unsupported strftime directive |
Error is #[non_exhaustive], so a match needs a wildcard arm:
1use pharaonic_hijri::{Error, HijriDate}; 2 3fn describe(input: &str) -> String { 4 match input.parse::<HijriDate>() { 5 Ok(date) => format!("valid: {date}"), 6 Err(Error::Parse) => "use the YYYY-MM-DD format".to_owned(), 7 Err(Error::InvalidDate) => "that day doesn't exist".to_owned(), 8 Err(error) => error.to_string(), 9 }10}11 12fn main() {13 assert_eq!(describe("1445-9-1"), "valid: 1445-09-01");14 assert_eq!(describe("01/09/1445"), "use the YYYY-MM-DD format");15 assert_eq!(describe("1445-02-30"), "that day doesn't exist");16 assert_eq!(describe("0-01-01"), "date is outside the supported range");17}#API Reference
Everything is imported from the crate root: use pharaonic_hijri::{Converter, Error, HijriDate, Language};. The full reference, with an example for every item, is on docs.rs.
#HijriDate
| Method | Description | Returns |
|---|---|---|
HijriDate::new(year: i16, month: i8, day: i8) | A date from its parts | Result<HijriDate, Error> |
HijriDate::from_gregorian(date: impl Into<civil::Date>) | Converts a Jiff Date, DateTime or ZonedDateTime with the default adjustment | Result<HijriDate, Error> |
to_gregorian(self) | Converts back with the default adjustment | Result<civil::Date, Error> |
year(self) | The year | i16 |
month(self) | The month, 1 to 12 | i8 |
day(self) | The day of the month | i8 |
month_name(self, language: Language) | The month's name | &'static str |
is_leap_year(self) | Whether the year has 355 days | bool |
days_in_month(self) | 29 or 30 | i8 |
days_in_year(self) | 354 or 355 | i16 |
day_of_year(self) | 1 to 355 | i16 |
checked_add_days(self, days: i32) | Adds days, negative to go back | Result<HijriDate, Error> |
checked_add_months(self, months: i32) | Adds months, keeping the day or the month's last day | Result<HijriDate, Error> |
checked_add_years(self, years: i32) | Adds years, like checked_add_months | Result<HijriDate, Error> |
days_until(self, other: HijriDate) | Days to other, negative when earlier | i32 |
months_until(self, other: HijriDate) | Whole months to other | i32 |
years_until(self, other: HijriDate) | Whole years to other | i32 |
strftime(self, format: &str, language: Language) | Formats with the strftime directives | Result<String, Error> |
| Constant / trait | Description |
|---|---|
HijriDate::MIN / HijriDate::MAX | 0001-01-01 and 9999-12-29 |
Display | YYYY-MM-DD |
FromStr | Parses YYYY-MM-DD |
Copy, Eq, Ord, Hash, Debug | Compare, sort and hash dates |
Serialize, Deserialize | With the serde feature: the YYYY-MM-DD string |
#Converter
| Item | Description | Returns |
|---|---|---|
Converter::new(adjustment: i32) | A converter with an adjustment in days | Converter |
Converter::default() | The default adjustment | Converter |
Converter::DEFAULT_ADJUSTMENT | -1 | i32 |
adjustment(self) | Its adjustment | i32 |
to_hijri(self, date: impl Into<civil::Date>) | Gregorian to Hijri | Result<HijriDate, Error> |
to_gregorian(self, date: HijriDate) | Hijri to Gregorian | Result<civil::Date, Error> |
#Language
| Variant | Month names |
|---|---|
Language::Arabic | مُحرَّم … ذو الحِجّة |
Language::English | Muharram … Dhu Al-Hijjah |
Language is #[non_exhaustive]: more languages may be added in a minor release.
#Error
| Variant | Description |
|---|---|
Error::InvalidDate | The month or the day doesn't exist |
Error::OutOfRange | Outside the supported range |
Error::Parse | Not a YYYY-MM-DD string |
Error::UnknownDirective | An unsupported strftime directive |
See Errors for when each one happens.
#Coming from PHP Hijri
The crate is the Rust port of the PHP Hijri package. The conversions match, including the default adjustment of -1, so a date stored by a PHP app reads the same in a Rust one.
| PHP Hijri | Rust |
|---|---|
Carbon::parse('2024-03-11')->toHijri() | HijriDate::from_gregorian(date(2024, 3, 11))? |
Carbon::fromHijri(1445, 9, 1) | HijriDate::new(1445, 9, 1)?.to_gregorian()? |
Carbon::parseHijri('1445-09-01') | "1445-09-01".parse::<HijriDate>()?.to_gregorian()? |
$hijri->toGregorian() | hijri.to_gregorian()? |
$hijri->year, ->month, ->day | hijri.year(), .month(), .day() |
$hijri->addDays(1) | hijri.checked_add_days(1)? |
$hijri->addMonthsNoOverflow(1) | hijri.checked_add_months(1)? |
$hijri->diffInMonths($other) | hijri.months_until(other) |
$hijri->isLeapYear() | hijri.is_leap_year() |
$hijri->format('j F Y') | hijri.strftime("%-d %B %Y", Language::English)? |
Hijri::setHijriAdjustment(0) (global) | Converter::new(0) (a value you pass) |
#Deliberate Differences
- No global adjustment. A
Convertercarries any adjustment other than the default. - Months don't overflow.
checked_add_monthskeeps the day or uses the month's last day, likeaddMonthsNoOverflow(). Carbon's defaultaddMonth()overflows into the next month instead. - Dates only. A
HijriDatehas no time or time zone. Parsing doesn't accept theHH:MM[:SS]part thatparseHijri()reads: add the time to the Gregorian date with Jiff. - strftime, not PHP format characters.
%jcounts from 1 where PHP'szcounts from 0, and weekday names come from the Gregorian date through Jiff. - Language is an argument. Month names follow the
Languageyou pass, not a locale.
#Examples
#1. Ramadan and Eid Dates
List when Ramadan starts and when Eid al-Fitr falls for the next few Hijri years:
1use pharaonic_hijri::{Error, HijriDate}; 2 3fn main() -> Result<(), Error> { 4 let mut lines = Vec::new(); 5 6 for year in 1445..=1447 { 7 let ramadan = HijriDate::new(year, 9, 1)?; 8 let eid = HijriDate::new(year, 10, 1)?; 9 10 lines.push(format!(11 "{year}: Ramadan {}, {} days, Eid {}",12 ramadan.to_gregorian()?,13 ramadan.days_in_month(),14 eid.to_gregorian()?,15 ));16 }17 18 assert_eq!(lines[0], "1445: Ramadan 2024-03-11, 30 days, Eid 2024-04-10");19 20 Ok(())21}#2. An Arabic Date Label
Show a record's date the way an Arabic interface writes it:
1use jiff::civil::date; 2use pharaonic_hijri::{HijriDate, Language}; 3 4fn arabic_label(day: jiff::civil::Date) -> Result<String, pharaonic_hijri::Error> { 5 HijriDate::from_gregorian(day)?.strftime("%-d %B %Y هـ", Language::Arabic) 6} 7 8fn main() -> Result<(), pharaonic_hijri::Error> { 9 assert_eq!(arabic_label(date(2024, 3, 11))?, "1 رَمضان 1445 هـ");10 11 Ok(())12}#3. Hijri Dates in a JSON API
Return a record's created_at with its Hijri date, read in the user's time zone. This uses the serde feature.
1[dependencies]2jiff = { version = "1", features = ["serde"] }3pharaonic-hijri = { version = "1", features = ["serde"] }4serde = { version = "1", features = ["derive"] }5serde_json = "1" 1use jiff::tz::TimeZone; 2use jiff::Timestamp; 3use pharaonic_hijri::HijriDate; 4use serde::Serialize; 5 6#[derive(Serialize)] 7struct PostResource { 8 id: u64, 9 created_at: Timestamp,10 created_at_hijri: HijriDate,11}12 13fn resource(id: u64, created_at: Timestamp, tz: TimeZone) -> Result<PostResource, pharaonic_hijri::Error> {14 let created_at_hijri = HijriDate::from_gregorian(created_at.to_zoned_datetime(tz))?;15 16 Ok(PostResource { id, created_at, created_at_hijri })17}18 19fn main() -> Result<(), Box<dyn std::error::Error>> {20 let created_at: Timestamp = "2024-03-10T22:30:00Z".parse()?;21 let post = resource(7, created_at, TimeZone::get("Africa/Cairo")?)?;22 23 assert_eq!(24 serde_json::to_string(&post)?,25 r#"{"id":7,"created_at":"2024-03-10T22:30:00Z","created_at_hijri":"1445-09-01"}"#26 );27 28 Ok(())29}#4. Age in Hijri Years
1use jiff::civil::date; 2use pharaonic_hijri::{Error, HijriDate}; 3 4fn hijri_age(birthday: jiff::civil::Date, today: jiff::civil::Date) -> Result<i32, Error> { 5 Ok(HijriDate::from_gregorian(birthday)?.years_until(HijriDate::from_gregorian(today)?)) 6} 7 8fn main() -> Result<(), Error> { 9 // 1990-01-01 is 1410-06-04, and 2026-10-07 is 1448-04-25.10 assert_eq!(hijri_age(date(1990, 1, 1), date(2026, 10, 7))?, 37);11 12 Ok(())13}#5. Validating User Input
Read a Hijri date from a form and turn every failure into a message:
1use pharaonic_hijri::{Error, HijriDate}; 2 3fn validate(input: &str) -> Result<jiff::civil::Date, String> { 4 let date: HijriDate = input.parse().map_err(|error: Error| match error { 5 Error::Parse => "Write the date as YYYY-MM-DD.".to_owned(), 6 Error::InvalidDate => "That day doesn't exist in the Hijri calendar.".to_owned(), 7 other => other.to_string(), 8 })?; 9 10 date.to_gregorian().map_err(|error| error.to_string())11}12 13fn main() {14 assert_eq!(validate("1445-09-01"), Ok(jiff::civil::date(2024, 3, 11)));15 assert_eq!(validate("1445-02-30"), Err("That day doesn't exist in the Hijri calendar.".to_owned()));16}#Troubleshooting
#The Hijri date is one day off
The tabular calendar can differ from the calendar announced where you live by a day or two, and the default adjustment is -1. Use a Converter with the adjustment that matches your calendar, such as Converter::new(0). See Day Adjustment.
#A record's date is a day off for some users
A Timestamp was read in the wrong time zone. Convert it in the user's time zone, not UTC: HijriDate::from_gregorian(created_at.to_zoned_datetime(tz)). See Timestamps and created_at.
#the trait bound Date: From<Timestamp> is not satisfied
from_gregorian doesn't take a Timestamp, because an instant has no date of its own. Choose a time zone first with to_zoned_datetime(tz).
#HijriDate: Serialize is not satisfied
The serde feature is off by default. Enable it: pharaonic-hijri = { version = "1", features = ["serde"] }.
#strftime returns Error::UnknownDirective
Only the listed directives are supported. Weekdays (%A) and times (%H, %M) belong to the Gregorian date: format them with Jiff. A trailing or unknown % needs %%.
#Error::OutOfRange from a conversion
The date is outside what both calendars can hold: before July 19, 622, after 9999 AH, or a Hijri date whose Gregorian day is after December 31, 9999.
#Upgrade Guide
#1.x
1.0.0 is the first release of the crate. There are no upgrade steps yet.
Coming from the PHP package? See Coming from PHP Hijri for the API mapping and the deliberate differences.
Contributors
Amazing people who made this package possible
This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Rust Hijri!
Want to Contribute?
We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.
Was this page helpful?
Thanks, that helps us decide what to improve.
Something wrong or missing? Report it on GitHub .