php-dates 0.2.1

PHP date() patterns for Rust: strict createFromFormat-style parsing, a pattern resolution contract and a Day.js export, with no framework dependency
Documentation
# php-dates

PHP date patterns for Rust: format with the tokens of `DateTime::format()` and parse with the rules of
`DateTime::createFromFormat()`. It uses [`jiff`](https://crates.io/crates/jiff), the date library of Laravel for Rust, and
has no framework or database dependency.

```rust
use php_dates::{PhpDatePattern, PhpDateTime, Zone, jiff};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pattern = PhpDatePattern::compile(r"l \t\h\e jS \of F Y, g:ia")?;

    // Format
    let date: jiff::civil::DateTime = "2026-02-03T16:05:00".parse()?;
    assert_eq!(pattern.format(date), "Tuesday the 3rd of February 2026, 4:05pm");

    // Parse, like DateTime::createFromFormat()
    let now = PhpDateTime::new("2026-03-15T10:20:30".parse()?, Zone::Utc)?;
    let parsed = PhpDatePattern::compile("Y-m-d H:i:s e")?.parse_at("2026-02-10 13:05:09 Europe/Madrid", &now)?;
    assert_eq!(parsed.offset_seconds(), 3600);
    Ok(())
}
```

## Install

```toml
[dependencies]
php-dates = "0.2"
```

Requires Rust 1.85 or later. The major version of `jiff` is the one `laravel-rust` uses, so a `jiff::civil::DateTime`,
`Timestamp` or `ZonedDateTime` from the framework goes straight in; `php_dates::jiff` re-exports it.

### Time zone data

Named zones come from the system's time zone database (jiff embeds one on Windows and WebAssembly). On a Linux image
without `tzdata` (distroless, `scratch`) enable `tzdb-bundle`:

```toml
[dependencies]
php-dates = { version = "0.2", features = ["tzdb-bundle"] }
```

Debian 13 and Ubuntu 24.04 moved old names out of `tzdata`: `Cuba`, `Egypt`, `GB`, `Japan`, `Zulu`, `UCT`, `GMT0`,
`US/Eastern` and the like need the `tzdata-legacy` package there. Without it `Zone::parse` returns `None` for them, and
`tzdb-bundle` does not help while the system has a database. The tests need the package too.

Offsets and abbreviations of named zones are as recent as that database, so they can differ from those of a PHP that
ships another release, mostly before 1970 and in zones whose rules changed lately.

## Tokens

All the tokens of PHP 8.5's `DateTime::format()` are supported, in English.

| | Tokens |
|---|---|
| Day | `d D j l N S w z` |
| Week | `W` |
| Month | `F m M n t` |
| Year | `L o X x Y y` |
| Time | `a A B g G h H i s u v` |
| Time zone | `e I O P p T Z` |
| Full | `c r U` |
| Escape | `\` |

`format` prints them as PHP does. A character that is not a token is printed as it is, including the letters PHP does
not use.

`createFromFormat()` reads `d D j l S z F m M n Y y X x a A g h G H i s v u e T O P p U` and these pattern characters:

| Character | Reads |
|---|---|
| space | Zero or more spaces, tabs and non-breaking spaces |
| `#` | One of `;:/.,-()` |
| `?` | Any one character |
| `*` | At least one character, then up to the next digit, space, tab or `;:/.,-` |
| `!` | Resets every field to the Unix epoch |
| `\|` | Resets the fields the value did not set |
| `+` | Nothing; PHP only warns about data left over when the pattern has it (an error here, see below) |

When the value ends before the pattern does, only `!`, `|` and `+` may remain.

`!` keeps what PHP keeps: a day name already read, and a zone given as an offset or an abbreviation. A zone given as an
identifier is dropped for the zone of `now`.

`D` and `l` read a day name, its plural or its three-letter form (not `Tues` or `Thurs`); `F` and `M` also read Roman
numerals, as PHP does.

`N w W o t L B I Z c r` only format. Parsing a pattern that has one is an error; `is_parseable()` tells beforehand.

## Formatting

```rust
use php_dates::{PhpDatePattern, PhpDateTime, jiff::civil::date};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pattern = PhpDatePattern::compile("d/m/Y H:i")?;
    let moment = date(2026, 2, 10).at(13, 5, 0, 0);

    assert_eq!(pattern.format(moment), "10/02/2026 13:05");

    // Into a buffer you own, or inside another string, without a String in between.
    let value = PhpDateTime::from(moment);
    let mut line = String::new();
    pattern.format_into(&mut line, &value)?;
    assert_eq!(format!("at {}", pattern.formatted(&value)), format!("at {line}"));
    Ok(())
}
```

`format` takes anything that becomes a `PhpDateTime`:

- a `jiff::civil::DateTime`, read as UTC
- a `jiff::Timestamp`, in UTC
- a `jiff::ZonedDateTime`, in its own zone
- a `PhpDateTime`, built with `PhpDateTime::new(local, zone)`, `from_timestamp(timestamp, zone)` or `from_utc(utc, zone)`

A compiled pattern is `Send + Sync`: compile once and share it. `as_str()`, `Display` and `FromStr` give and take the
pattern text.

## Skipped and repeated hours

A wall-clock time that does not exist in a named zone (the hour a daylight saving change skips) moves forward, as in
PHP. A time that happens twice is the **first** one.

PHP is not consistent there. For `new DateTime($time, $zone)`, or a `createFromFormat()` value that names no zone, it
takes the **second** when the clocks go back to UTC+0 or ahead of it (`Europe/London`, `Europe/Lisbon`,
`Europe/Madrid`, `Australia/Sydney`) and the first when they stay behind it (`Atlantic/Azores`, `America/Matamoros`).
When the value names the zone it usually takes the first, but not always (`Europe/Dublin` and `Africa/Casablanca` give
the second). This crate does not copy that. Choose when it matters:

```rust
use php_dates::{PhpDateTime, Zone, jiff::civil::date, jiff::tz::Disambiguation};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let madrid = Zone::parse("Europe/Madrid").ok_or("unknown zone")?;
    let twice = date(2026, 10, 25).at(2, 30, 0, 0);

    assert_eq!(PhpDateTime::new(twice, madrid.clone())?.offset_seconds(), 7200);
    let second = PhpDateTime::new_with(twice, madrid.clone(), Disambiguation::Later)?;
    assert_eq!(second.offset_seconds(), 3600);
    assert!(PhpDateTime::new_with(twice, madrid, Disambiguation::Reject).is_err());
    Ok(())
}
```

`parse_at_with` takes the same choice when reading a value.

## Parsing

`pattern.parse_at(value, &now)` is `DateTime::createFromFormat($pattern, $value, $zone)` with a given "now", and
`pattern.parse_now(value, &zone)` the same with the system clock.

- The fields the value leaves out come from `now`. If the value sets an hour, a minute or a second, the time fields it
  leaves out are zero; if it sets any date or time field, so are the microseconds it does not give.
- A zone in the value (`e T O P p U`) only labels the result; the fields taken from `now` are not converted.
- The zone of `now` is the one the result has when the value names none.
- Errors are a `ParseError { position, message }`, with PHP's wording where PHP has one.

### Where it is stricter than PHP

PHP reports these as warnings and still returns a date. Here they are errors, as if you had checked
`DateTime::getLastErrors()`:

- A date that does not exist: `31/02/2026`. (A date without a year or a month and a day rolls over, as in PHP.)
- An hour above 23, a minute or a second above 59.
- Trailing data, which PHP only accepts with a warning when the pattern ends with `+`.

And these PHP accepts without a warning, but only by accident:

- Characters skipped between the sign of `U`, `X` or `x` and its digits.
- A unit of time as a day name (`month`, `week`).
- Offsets that are not one of the shapes below, or have minutes or seconds above 59 (`+0299`, `+10:00:`).

### Where it differs from PHP

- Names are English. There is no locale.
- Years go from `-9999` to `9999`, the range of jiff. Offsets go up to `±25:59:59`. A `U` outside that range is an
  error where it is read, even if a later `!` would discard it.
- `?` reads one character; PHP reads one byte.
- `N w W o t L B I Z c r` are an error when parsing; PHP treats them as literal characters.
- Time zone abbreviations are a short list of common ones (see below). Identifiers and offsets are complete.
- `KST` is `+09:00` and `NDT` is `-02:30`; PHP's table says `+08:30` and `-02:30:52`.
- An identifier is printed with the capitals of the database, not the capitals of the value.
- `z` after a time field makes PHP normalize fields that have no value yet, which moves the date by centuries. It is
  not copied.
- Repeated hours, as above.

## The strict reader

`PhpDatePattern::parse(value)` is for validating input, such as a filter payload: it reads like
`createFromFormat('!' . $pattern, $value)` and then requires that the date formats back to exactly the same text, so
`2/2026` is not `m/Y` and `10/02/2026 ` is not `d/m/Y`. It returns a `jiff::civil::DateTime`, with the fields the pattern
leaves out at the Unix epoch.

- A 12-hour pattern (`h` or `g`) without `a` or `A` is always `None`: `01:30` does not say which half of the day.
- A zone the pattern reads (`Y-m-d H:i P`) is checked and then dropped: the result is the wall-clock time. Use
  `parse_at` to keep the zone.
- `y` reads `00`-`69` as 2000-2069 and `70`-`99` as 1970-1999, as PHP does. A year outside 1970-2069 written with `y`
  reads back as another one, so do not store birth dates or other old dates with a two-digit pattern, including the
  `d/m/y` fallback.

## Checking a pattern

`compile` reads a pattern as PHP does: a letter that is not a token is a literal. `compile_strict` rejects it, which
catches typos in patterns that people type:

```rust
use php_dates::PhpDatePattern;

assert!(PhpDatePattern::compile("Y-m-d q").is_ok()); // prints "2026-02-10 q"
assert!(PhpDatePattern::compile_strict("Y-m-d q").is_err());
assert!(!PhpDatePattern::compile("Y-W").map(|pattern| pattern.is_parseable()).unwrap_or(true));
```

## Time zones

`Zone` is PHP's three kinds of zone:

```rust
use php_dates::Zone;

assert!(Zone::parse("Europe/Madrid").is_some()); // an identifier, in any letter case
assert!(Zone::parse("CEST").is_some()); // an abbreviation
assert_eq!(Zone::parse("+05:30"), Some(Zone::Offset(19_800))); // an offset
assert_eq!(Zone::parse("GMT+2"), Some(Zone::Offset(7200)));
assert_eq!(Zone::parse("UTC+2"), None);
```

Offsets are `+H`, `+HH`, `+H:`, `+HH:`, `+H:M`, `+HMM`, `+H:MM`, `+HH:M`, `+HHMM`, `+HH:MM`, `+HHMMSS` and
`+HH:MM:SS`, optionally after `GMT` in capitals. Inside a value, `createFromFormat()` also skips spaces and parentheses:
`(CET)`.

The abbreviations are `Z GMT EST EDT CST CDT MST MDT PST PDT AKST AKDT HST AST ADT NST NDT WET WEST BST CET CEST EET
EEST SAST MSK HKT JST KST AWST ACST ACDT AEST AEDT NZST NZDT`, and `UTC`. PHP knows many more, several of them
ambiguous (`IST`), and the military letters. `T` of a named zone can print one that is not in the list (`IST`, `+03`),
which cannot then be read back with `T`: use `e` or an offset to store zones.

A jiff zone without a name, such as a POSIX `TZ` string, is kept with its rules; `e` prints its offset.

`PhpDateTime` has `datetime()`, `zone()`, `offset_seconds()`, `is_dst()`, `abbreviation()`, `timestamp()`,
`to_timestamp()`, `to_zoned_datetime()` and `in_zone(zone)`. `timestamp()` (`U`) is rounded down, as in PHP, and covers
every wall-clock time; jiff's `Timestamp` ends a little before the year 10000, so `to_timestamp()` and
`to_zoned_datetime()` are errors for the last day or so.

## Pattern resolution and Day.js

`formats` decides which pattern applies from a `DateConfig` (one pattern per kind and purpose, plus legacy settings) and
exports patterns to [Day.js](https://day.js.org) for a frontend:

```rust
use php_dates::{DateConfig, formats::{self, Kind, Purpose}};

fn main() -> Result<(), php_dates::Error> {
    let config = DateConfig::default();
    assert_eq!(formats::format(&config, Kind::Date, Purpose::Filter, None)?, "d/m/Y");
    assert_eq!(formats::to_dayjs("D, d M Y H:i:s O")?, "ddd, DD MMM YYYY HH:mm:ss ZZ");
    formats::frontend_config(&config)?; // JSON with every pattern in Day.js tokens
    assert_eq!(Kind::Date.cast_fallback(), "d/m/y");
    Ok(())
}
```

`to_dayjs` translates `Y y m n d j H G h g i s a A D l M F w v O P U` and escaped literals. `U` needs Day.js's
`advancedFormat` plugin. It rejects the tokens Day.js cannot express (`B t S z L ...`) instead of generating an
incompatible pattern. It also rejects two tokens that Day.js would read as others when written together (`nm` would
be `MMM`, `jj` `DD`, `GH` `HHH`): put a character between them.

Resolution order for a kind (`Date`, `DateTime`, `Month`) and a purpose (`Display`, `Value`, `Filter`): `value.<kind>` or
`filter.<kind>` for the purpose, then `<kind>`, then the legacy `date_format_solo` (date) or `date_format` (date-time),
then the fallback the caller passes, then the default (`d/m/Y`, `d/m/Y h:i a`, `m/Y`).

Deserializing a `DateConfig` ignores keys it does not know, so a typo leaves a pattern unset. Check settings people write
with `DateConfig::unknown_keys(&json)`.

## Tested against PHP

The tests compare the answers with PHP 8.5.0's, recorded in two fixtures:

- `tests/fixtures/php_oracle.json` (`generate.php`): 9,996 formatting cases (every token, in 12 moments and 17 zones) and
  3,288 `createFromFormat` cases.
- `tests/fixtures/php_oracle_edges.json` (`generate_edges.php`): the strict reader, pattern characters with damaged
  values, daylight saving changes, the ends of the calendar, years before Christ and zone strings.

The known differences above are left out by the generators, one function each, so that any other difference fails.

```sh
cargo test
tests/differential.sh 20                                   # fresh random cases from the PHP on this machine
DAYJS=/path/to/node_modules/dayjs cargo test --test dayjs -- --ignored   # exported patterns, with Node
PROPTEST_CASES=100000 cargo test --release --test properties
cargo +nightly fuzz run parse                              # also: zone, dayjs
cargo bench --bench patterns
```

The repository has these tests; the published package does not.

## License

MIT. See [LICENSE.md](LICENSE.md).