php-dates 0.2.0

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};

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);
```

## Install

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

Requires Rust 1.99 or later. The version of `jiff` is the one `laravel-rust` uses, so a `jiff::civil::DateTime`,
`Timestamp` or `ZonedDateTime` from the framework goes straight in.

## 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 |
| `*` | Anything up to the next digit, space or `;:/.,-()` |
| `!` | Resets every field to the Unix epoch |
| `\|` | Resets the fields the value did not set |
| `+` | Trailing data (an error here, see below) |

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

## Formatting

```rust
pattern.format(value)
```

`value` is 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 wall-clock time that does not exist in a zone (the hour a daylight saving change skips) moves forward, and one that
happens twice is the first, as PHP does.

## Parsing

```rust
pattern.parse_at(value, &now)   // DateTime::createFromFormat($pattern, $value, $zone), with a given "now"
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.
- 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 `+`.
- Numbers must start where the token is. PHP skips characters before a digit in some tokens.

### 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`.
- Time zone abbreviations are a list of common ones (`EST`, `CEST`, `GMT`, ...). Identifiers and offsets are complete.
  An ambiguous abbreviation such as `IST` is rejected; use an identifier or an offset.
- An identifier is printed with the capitals of the database, not the capitals of the value.
- `z` after a time field that was set alone, and some unsigned `X`, behave in PHP in ways that look like bugs (it
  normalizes fields that have no value). They are not copied.

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

## 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
assert!(PhpDatePattern::compile("Y-m-d q").is_ok());      // prints "2026-02-10 q"
assert!(PhpDatePattern::compile_strict("Y-m-d q").is_err());
```

## Time zones

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

```rust
Zone::parse("Europe/Madrid")   // an identifier, in any letter case
Zone::parse("CEST")            // an abbreviation
Zone::parse("+05:30")          // an offset: +H, +HH, +HMM, +HHMM, +HH:MM, +HHMMSS, +HH:MM:SS, and GMT+2
```

`PhpDateTime` has `datetime()`, `zone()`, `offset_seconds()`, `is_dst()`, `timestamp()`, `to_timestamp()`,
`to_zoned_datetime()` and `in_zone(zone)`.

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

let config = DateConfig::default();
formats::format(&config, Kind::Date, Purpose::Filter, None)?;   // "d/m/Y"
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
```

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

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

## Tested against PHP

The tests compare every answer with PHP 8.5.0's. `tests/fixtures/php_oracle.json` holds 9,996 formatting cases (every
token, in 12 moments and 17 zones) and 3,288 `createFromFormat` cases (hand-written, and random patterns formatted and
read back by PHP). Regenerate it with the PHP on your machine:

```sh
php tests/fixtures/generate.php            # SEED=1 COUNT=4000 php ... for more random cases
cargo test
```

## License

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