# Rust Hijri documentation (v1.x)

> Canonical: https://pharaonic.dev/packages/rust/hijri/1.x  
> Version: v1.x (latest release 1.0.0, 2026-12-02)  
> Install: cargo add pharaonic-hijri  
> Requires: Rust 1.98+  
> Repository: https://github.com/Pharaonic/rust-hijri  
> All versions: https://pharaonic.dev/packages/rust/hijri/1.x.md

:::badges
- Rust Crate {color=blue}
- v1.0.0 {color=green}
- MIT License {color=purple}
:::

# Rust Hijri

Hijri (Islamic) calendar dates for Rust, built on [Jiff](https://docs.rs/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.

:::features
### 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.
:::

:::info Quick Tip
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](https://docs.rs/jiff) 1.x, whose dates the crate converts

### Cargo Installation

```bash title="Terminal" no-line-numbers
cargo add pharaonic-hijri jiff
```

Or add the dependencies to `Cargo.toml` yourself:

```toml title="Cargo.toml"
[dependencies]
jiff = "1"
pharaonic-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:

```bash title="Terminal" no-line-numbers
cargo add pharaonic-hijri --features serde
```

See [Cargo Features](#features) for details.

:::success Installation Complete
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.

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::{Error, HijriDate, Language};

fn main() -> Result<(), Error> {
    // Gregorian to Hijri.
    let ramadan = HijriDate::from_gregorian(date(2024, 3, 11))?;

    assert_eq!(ramadan.to_string(), "1445-09-01");
    assert_eq!((ramadan.year(), ramadan.month(), ramadan.day()), (1445, 9, 1));
    assert_eq!(ramadan.month_name(Language::English), "Ramadan");

    // Hijri date math.
    let eid = ramadan.checked_add_months(1)?;

    assert_eq!(eid.to_string(), "1445-10-01");

    // Hijri to Gregorian.
    assert_eq!(eid.to_gregorian()?, date(2024, 4, 10));

    // Formatting.
    assert_eq!(eid.strftime("%-d %B %Y", Language::Arabic)?, "1 شوّال 1445");

    Ok(())
}
```

Every conversion uses the default adjustment of one day back, the same as the PHP package. [Day Adjustment](#adjustment) explains it and how to use another one.

:::tip Copy and compare freely
`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:

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::{Converter, Error, HijriDate};

fn main() -> Result<(), Error> {
    let today = date(2024, 3, 11);

    assert_eq!(HijriDate::from_gregorian(today)?.to_string(), "1445-09-01"); // -1
    assert_eq!(Converter::new(0).to_hijri(today)?.to_string(), "1445-09-02");
    assert_eq!(Converter::new(1).to_hijri(today)?.to_string(), "1445-09-03");

    // The same converter turns its Hijri dates back into the same Gregorian ones.
    let converter = Converter::new(0);
    let hijri = converter.to_hijri(today)?;

    assert_eq!(converter.to_gregorian(hijri)?, today);

    Ok(())
}
```

### 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:

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::{Converter, Error, HijriDate};

struct Settings {
    hijri: Converter,
}

fn ramadan_start(settings: &Settings, year: i16) -> Result<jiff::civil::Date, Error> {
    settings.hijri.to_gregorian(HijriDate::new(year, 9, 1)?)
}

fn main() -> Result<(), Error> {
    let settings = Settings { hijri: Converter::new(0) };

    assert_eq!(ramadan_start(&settings, 1445)?, date(2024, 3, 10));

    Ok(())
}
```

:::info Why the default is -1
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`.

```rust title="src/main.rs"
use jiff::civil::date;
use jiff::ZonedDateTime;
use pharaonic_hijri::HijriDate;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let expected = HijriDate::new(1445, 9, 1)?;

    // A date.
    assert_eq!(HijriDate::from_gregorian(date(2024, 3, 11))?, expected);

    // A date and time: the time doesn't change the day.
    assert_eq!(HijriDate::from_gregorian(date(2024, 3, 11).at(23, 59, 0, 0))?, expected);

    // A zoned date and time, read in its own time zone.
    let zoned: ZonedDateTime = "2024-03-11T08:00[Asia/Riyadh]".parse()?;

    assert_eq!(HijriDate::from_gregorian(zoned)?, expected);

    Ok(())
}
```

### 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:

```rust title="src/main.rs"
use jiff::tz::TimeZone;
use jiff::Timestamp;
use pharaonic_hijri::HijriDate;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 22:30 UTC on March 10 is already March 11 in Cairo.
    let created_at: Timestamp = "2024-03-10T22:30:00Z".parse()?;

    let in_utc = HijriDate::from_gregorian(created_at.to_zoned_datetime(TimeZone::UTC))?;
    let in_cairo = HijriDate::from_gregorian(created_at.to_zoned_datetime(TimeZone::get("Africa/Cairo")?))?;

    assert_eq!(in_utc.to_string(), "1445-08-29");
    assert_eq!(in_cairo.to_string(), "1445-09-01");

    Ok(())
}
```

### Range

Hijri dates start on 1 Muharram 1 AH, July 19, 622 with the default adjustment. An earlier Gregorian date returns `Error::OutOfRange`.

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::{Error, HijriDate};

fn main() {
    assert_eq!(HijriDate::from_gregorian(date(622, 7, 19)), Ok(HijriDate::MIN));
    assert_eq!(HijriDate::from_gregorian(date(600, 1, 1)), Err(Error::OutOfRange));
}
```

## 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`.

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::{Error, HijriDate};

fn main() -> Result<(), Error> {
    let eid = HijriDate::new(1445, 10, 1)?;

    assert_eq!(eid.to_gregorian()?, date(2024, 4, 10));

    let parsed: HijriDate = "1413-08-08".parse()?;

    assert_eq!(parsed.to_gregorian()?, date(1993, 2, 1));

    Ok(())
}
```

### 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.

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn main() {
    assert!(HijriDate::new(1445, 1, 30).is_ok());
    assert_eq!(HijriDate::new(1445, 2, 30), Err(Error::InvalidDate)); // Safar 1445 has 29 days
    assert_eq!(HijriDate::new(1445, 13, 1), Err(Error::InvalidDate));
    assert_eq!(HijriDate::new(0, 1, 1), Err(Error::OutOfRange)); // years 1 to 9999
}
```

### Parsing Strings

`HijriDate` implements `FromStr` for `YYYY-MM-DD` strings. Single-digit months and days, and surrounding whitespace, are accepted:

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn main() {
    assert_eq!("1445-09-01".parse::<HijriDate>(), HijriDate::new(1445, 9, 1));
    assert_eq!(" 1445-9-1 ".parse::<HijriDate>(), HijriDate::new(1445, 9, 1));
    assert_eq!("1445/09/01".parse::<HijriDate>(), Err(Error::Parse));
    assert_eq!("1445-02-30".parse::<HijriDate>(), Err(Error::InvalidDate));
}
```

### Adding a Time

The crate works with dates. Add the time on the Gregorian side with Jiff:

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::HijriDate;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let iftar = "1445-09-01".parse::<HijriDate>()?.to_gregorian()?.at(18, 5, 0, 0);

    assert_eq!(iftar, date(2024, 3, 11).at(18, 5, 0, 0));

    Ok(())
}
```

:::info Range
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

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn main() -> Result<(), Error> {
    let date = HijriDate::new(1445, 2, 29)?;

    assert_eq!(date.checked_add_days(1)?.to_string(), "1445-03-01");
    assert_eq!(date.checked_add_days(-29)?.to_string(), "1445-01-30");
    assert_eq!(date.checked_add_months(1)?.to_string(), "1445-03-29");
    assert_eq!(date.checked_add_years(-1)?.to_string(), "1444-02-29");

    Ok(())
}
```

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.

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn main() -> Result<(), Error> {
    // Muharram has 30 days, Safar 29.
    assert_eq!(HijriDate::new(1445, 1, 30)?.checked_add_months(1)?.to_string(), "1445-02-29");

    // 1445 is a leap year: Dhu Al-Hijjah 1445 has 30 days, 1446 has 29.
    assert_eq!(HijriDate::new(1445, 12, 30)?.checked_add_years(1)?.to_string(), "1446-12-29");

    Ok(())
}
```

### 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.

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn main() -> Result<(), Error> {
    let start = HijriDate::new(1445, 9, 1)?;
    let eid = HijriDate::new(1445, 10, 1)?;

    assert_eq!(start.days_until(eid), 30);
    assert_eq!(start.months_until(eid), 1);
    assert_eq!(start.months_until(HijriDate::new(1445, 9, 30)?), 0);
    assert_eq!(eid.days_until(start), -30);

    // An age in Hijri years.
    let born = HijriDate::new(1410, 6, 4)?;

    assert_eq!(born.years_until(HijriDate::new(1448, 6, 3)?), 37);
    assert_eq!(born.years_until(HijriDate::new(1448, 6, 4)?), 38);

    Ok(())
}
```

### Comparing Dates

Dates compare and sort chronologically. To compare a Hijri date with a Gregorian one, convert one side first:

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::{Error, HijriDate};

fn main() -> Result<(), Error> {
    let ramadan = HijriDate::new(1445, 9, 1)?;
    let today = HijriDate::from_gregorian(date(2024, 3, 20))?;

    assert!(today > ramadan);
    assert!(today < ramadan.checked_add_months(1)?);

    Ok(())
}
```

## Formatting

### Display

A `HijriDate` prints as `YYYY-MM-DD`, with the year padded to four digits. Parsing that string gives the same date back.

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn main() -> Result<(), Error> {
    let date = HijriDate::new(1445, 9, 1)?;

    assert_eq!(date.to_string(), "1445-09-01");
    assert_eq!(format!("Ramadan starts on {date}"), "Ramadan starts on 1445-09-01");
    assert_eq!(date.to_string().parse::<HijriDate>()?, date);

    Ok(())
}
```

### 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 `%` | `%` |

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate, Language};

fn main() -> Result<(), Error> {
    let date = HijriDate::new(1445, 9, 5)?;

    assert_eq!(date.strftime("%-d %B %Y", Language::English)?, "5 Ramadan 1445");
    assert_eq!(date.strftime("%d %B %Y هـ", Language::Arabic)?, "05 رَمضان 1445 هـ");
    assert_eq!(date.strftime("%Y/%m/%d", Language::English)?, "1445/09/05");

    // Any other directive is an error, never silently dropped.
    assert_eq!(date.strftime("%A", Language::English), Err(Error::UnknownDirective));

    Ok(())
}
```

### Weekdays and Times

The weekday and the time belong to the Gregorian date, so format them with Jiff and join the two:

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::{HijriDate, Language};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let day = date(2024, 3, 11);
    let hijri = HijriDate::from_gregorian(day)?;

    let label = format!("{}, {}", day.strftime("%A"), hijri.strftime("%-d %B %Y", Language::English)?);

    assert_eq!(label, "Monday, 1 Ramadan 1445");

    Ok(())
}
```

### 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 |

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate, Language};

fn main() -> Result<(), Error> {
    let date = HijriDate::new(1445, 12, 10)?;

    assert_eq!(date.month_name(Language::Arabic), "ذو الحِجّة");
    assert_eq!(date.month_name(Language::English), "Dhu Al-Hijjah");

    Ok(())
}
```

## 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:

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn main() -> Result<(), Error> {
    let date = HijriDate::new(1445, 9, 11)?;

    assert!(date.is_leap_year());
    assert_eq!(date.days_in_year(), 355);
    assert_eq!(date.days_in_month(), 30);
    assert_eq!(date.day_of_year(), 247);

    assert!(!HijriDate::new(1446, 1, 1)?.is_leap_year());

    Ok(())
}
```

### 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.

```toml title="Cargo.toml"
[dependencies]
pharaonic-hijri = { version = "1", features = ["serde"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
```

```rust title="src/main.rs"
use pharaonic_hijri::HijriDate;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Event {
    name: String,
    date: HijriDate,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let event = Event { name: "Eid al-Fitr".into(), date: HijriDate::new(1445, 10, 1)? };

    assert_eq!(serde_json::to_string(&event)?, r#"{"name":"Eid al-Fitr","date":"1445-10-01"}"#);

    let invalid = serde_json::from_str::<Event>(r#"{"name":"x","date":"1445-02-30"}"#);

    assert!(invalid.unwrap_err().to_string().contains("invalid hijri date"));

    Ok(())
}
```

## 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:

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn describe(input: &str) -> String {
    match input.parse::<HijriDate>() {
        Ok(date) => format!("valid: {date}"),
        Err(Error::Parse) => "use the YYYY-MM-DD format".to_owned(),
        Err(Error::InvalidDate) => "that day doesn't exist".to_owned(),
        Err(error) => error.to_string(),
    }
}

fn main() {
    assert_eq!(describe("1445-9-1"), "valid: 1445-09-01");
    assert_eq!(describe("01/09/1445"), "use the YYYY-MM-DD format");
    assert_eq!(describe("1445-02-30"), "that day doesn't exist");
    assert_eq!(describe("0-01-01"), "date is outside the supported range");
}
```

## 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](https://docs.rs/pharaonic-hijri).

### 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](#formatting) | `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](#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 `Converter` carries any adjustment other than the default.
- **Months don't overflow.** `checked_add_months` keeps the day or uses the month's last day, like `addMonthsNoOverflow()`. Carbon's default `addMonth()` overflows into the next month instead.
- **Dates only.** A `HijriDate` has no time or time zone. Parsing doesn't accept the `HH:MM[:SS]` part that `parseHijri()` reads: add the time to the Gregorian date with Jiff.
- **strftime, not PHP format characters.** `%j` counts from 1 where PHP's `z` counts from 0, and weekday names come from the Gregorian date through Jiff.
- **Language is an argument.** Month names follow the `Language` you 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:

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn main() -> Result<(), Error> {
    let mut lines = Vec::new();

    for year in 1445..=1447 {
        let ramadan = HijriDate::new(year, 9, 1)?;
        let eid = HijriDate::new(year, 10, 1)?;

        lines.push(format!(
            "{year}: Ramadan {}, {} days, Eid {}",
            ramadan.to_gregorian()?,
            ramadan.days_in_month(),
            eid.to_gregorian()?,
        ));
    }

    assert_eq!(lines[0], "1445: Ramadan 2024-03-11, 30 days, Eid 2024-04-10");

    Ok(())
}
```

### 2. An Arabic Date Label

Show a record's date the way an Arabic interface writes it:

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::{HijriDate, Language};

fn arabic_label(day: jiff::civil::Date) -> Result<String, pharaonic_hijri::Error> {
    HijriDate::from_gregorian(day)?.strftime("%-d %B %Y هـ", Language::Arabic)
}

fn main() -> Result<(), pharaonic_hijri::Error> {
    assert_eq!(arabic_label(date(2024, 3, 11))?, "1 رَمضان 1445 هـ");

    Ok(())
}
```

### 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.

- ===Cargo.toml

  ```toml title="Cargo.toml"
  [dependencies]
  jiff = { version = "1", features = ["serde"] }
  pharaonic-hijri = { version = "1", features = ["serde"] }
  serde = { version = "1", features = ["derive"] }
  serde_json = "1"
  ```

- ===src/main.rs

  ```rust title="src/main.rs"
  use jiff::tz::TimeZone;
  use jiff::Timestamp;
  use pharaonic_hijri::HijriDate;
  use serde::Serialize;

  #[derive(Serialize)]
  struct PostResource {
      id: u64,
      created_at: Timestamp,
      created_at_hijri: HijriDate,
  }

  fn resource(id: u64, created_at: Timestamp, tz: TimeZone) -> Result<PostResource, pharaonic_hijri::Error> {
      let created_at_hijri = HijriDate::from_gregorian(created_at.to_zoned_datetime(tz))?;

      Ok(PostResource { id, created_at, created_at_hijri })
  }

  fn main() -> Result<(), Box<dyn std::error::Error>> {
      let created_at: Timestamp = "2024-03-10T22:30:00Z".parse()?;
      let post = resource(7, created_at, TimeZone::get("Africa/Cairo")?)?;

      assert_eq!(
          serde_json::to_string(&post)?,
          r#"{"id":7,"created_at":"2024-03-10T22:30:00Z","created_at_hijri":"1445-09-01"}"#
      );

      Ok(())
  }
  ```

### 4. Age in Hijri Years

```rust title="src/main.rs"
use jiff::civil::date;
use pharaonic_hijri::{Error, HijriDate};

fn hijri_age(birthday: jiff::civil::Date, today: jiff::civil::Date) -> Result<i32, Error> {
    Ok(HijriDate::from_gregorian(birthday)?.years_until(HijriDate::from_gregorian(today)?))
}

fn main() -> Result<(), Error> {
    // 1990-01-01 is 1410-06-04, and 2026-10-07 is 1448-04-25.
    assert_eq!(hijri_age(date(1990, 1, 1), date(2026, 10, 7))?, 37);

    Ok(())
}
```

### 5. Validating User Input

Read a Hijri date from a form and turn every failure into a message:

```rust title="src/main.rs"
use pharaonic_hijri::{Error, HijriDate};

fn validate(input: &str) -> Result<jiff::civil::Date, String> {
    let date: HijriDate = input.parse().map_err(|error: Error| match error {
        Error::Parse => "Write the date as YYYY-MM-DD.".to_owned(),
        Error::InvalidDate => "That day doesn't exist in the Hijri calendar.".to_owned(),
        other => other.to_string(),
    })?;

    date.to_gregorian().map_err(|error| error.to_string())
}

fn main() {
    assert_eq!(validate("1445-09-01"), Ok(jiff::civil::date(2024, 3, 11)));
    assert_eq!(validate("1445-02-30"), Err("That day doesn't exist in the Hijri calendar.".to_owned()));
}
```

## 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](#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](#gregorian-to-hijri).

### `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](#formatting) 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](#coming-from-php) for the API mapping and the deliberate differences.
