Skip to main content

larust_support/
date.rs

1//! PHP/Laravel-style `date()` formatting - not a general date-parsing or
2//! date-arithmetic library, just enough to format an already-known
3//! `chrono::DateTime<Utc>` using PHP's own format-character vocabulary
4//! (`Y`, `m`, `d`, `F`, `j`, `S`, ...), so a converted Blade `date('Y-m-d')`
5//! call reads the same as the Laravel source it came from.
6//!
7//! Exists specifically as the target of `larust-convert`'s Blade
8//! expression translator (`larust_convert::blade::expr::translate`'s
9//! `"date"` function-call arm) - that translator only ever emits a call
10//! here after checking every character in the format string against the
11//! **same** recognized set [`format`] below implements (kept in sync by
12//! hand, documented on both sides, since the two live in separate crates
13//! with no shared table to enforce it structurally).
14//!
15//! [`strtotime`] is deliberately **not** a port of PHP's real
16//! `strtotime()` - that function accepts an enormous range of natural-
17//! language and relative date expressions ("next monday", "+3 days"),
18//! genuinely fuzzy parsing this framework's conversion tooling won't
19//! silently guess at. What's here only recognizes the common *machine-
20//! readable* timestamp shapes an Eloquent `created_at`/`updated_at`
21//! column actually serializes as - the one real, observed use this exists
22//! for (`strtotime($model['updated_at'])`) - and falls back to the
23//! current instant rather than failing when the string doesn't match one
24//! of them, a deliberate best-effort choice for this specific helper
25//! (unlike the *converter's* own convert-time refusals, which are about
26//! what's safe to auto-*generate*, not what's safe to *run*).
27
28use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, Utc};
29
30/// The current instant - `larust_support::date::now()`, Laravel's own
31/// `now()` helper (`rust-laravel.md`'s "helpers worth preserving" list).
32pub fn now() -> DateTime<Utc> {
33    Utc::now()
34}
35
36/// See this module's own doc comment for exactly what this does and
37/// doesn't cover. Tried in order: RFC 3339 (`2026-08-17T12:00:00Z`),
38/// MySQL/Eloquent's own `created_at`/`updated_at` format
39/// (`2026-08-17 12:00:00`), then a bare date (`2026-08-17`) - falls back
40/// to [`now`] if none match.
41pub fn strtotime(s: &str) -> DateTime<Utc> {
42    if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
43        return dt.with_timezone(&Utc);
44    }
45    if let Ok(naive) = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
46        return DateTime::from_naive_utc_and_offset(naive, Utc);
47    }
48    if let Ok(date) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
49        if let Some(naive) = date.and_hms_opt(0, 0, 0) {
50            return DateTime::from_naive_utc_and_offset(naive, Utc);
51        }
52    }
53    now()
54}
55
56/// Formats `when` using a PHP `date()`-style format string: each
57/// character is either one of the recognized format codes below or a
58/// literal passed through unchanged (PHP's own punctuation/whitespace
59/// convention - `date('Y-m-d')`'s `-` characters are literal, not format
60/// codes). Deliberately **not** a complete port of PHP's `date()` - only
61/// the common codes real Blade templates use; anything else is simply
62/// emitted literally, which is safe *here* only because
63/// `larust-convert`'s own converter-time check already rejects any format
64/// string containing a character outside this exact set before it ever
65/// generates a call to this function - nothing reaches this function at
66/// runtime that wasn't already vetted at convert time.
67pub fn format(when: DateTime<Utc>, php_format: &str) -> String {
68    let mut out = String::with_capacity(php_format.len());
69    for ch in php_format.chars() {
70        match ch {
71            'Y' => out.push_str(&when.format("%Y").to_string()),
72            'y' => out.push_str(&when.format("%y").to_string()),
73            'm' => out.push_str(&when.format("%m").to_string()),
74            'n' => out.push_str(&when.format("%-m").to_string()),
75            'd' => out.push_str(&when.format("%d").to_string()),
76            'j' => out.push_str(&when.format("%-d").to_string()),
77            'F' => out.push_str(&when.format("%B").to_string()),
78            'M' => out.push_str(&when.format("%b").to_string()),
79            'l' => out.push_str(&when.format("%A").to_string()),
80            'D' => out.push_str(&when.format("%a").to_string()),
81            'H' => out.push_str(&when.format("%H").to_string()),
82            'G' => out.push_str(&when.format("%-H").to_string()),
83            'h' => out.push_str(&when.format("%I").to_string()),
84            'g' => out.push_str(&when.format("%-I").to_string()),
85            'i' => out.push_str(&when.format("%M").to_string()),
86            's' => out.push_str(&when.format("%S").to_string()),
87            'A' => out.push_str(&when.format("%p").to_string()),
88            'a' => out.push_str(&when.format("%P").to_string()),
89            'N' => out.push_str(&when.format("%u").to_string()),
90            'w' => out.push_str(&when.format("%w").to_string()),
91            // The English ordinal suffix (`1st`, `2nd`, `3rd`, `4th`, ...,
92            // `11th`, `12th`, `13th`, `21st`, ...) - PHP's own `date('S')`.
93            // No `strftime` specifier expresses this (chrono included); a
94            // deterministic, mechanical computation from the day-of-month,
95            // not a guess.
96            'S' => out.push_str(ordinal_suffix(when.day())),
97            other => out.push(other),
98        }
99    }
100    out
101}
102
103/// `11`/`12`/`13` (and `111`/`112`/`113`, ...) are `"th"` even though they
104/// end in `1`/`2`/`3` - the standard English ordinal-suffix exception,
105/// checked via `% 100` before the normal `% 10` rule.
106fn ordinal_suffix(day: u32) -> &'static str {
107    match day % 100 {
108        11..=13 => "th",
109        _ => match day % 10 {
110            1 => "st",
111            2 => "nd",
112            3 => "rd",
113            _ => "th",
114        },
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use chrono::TimeZone;
122
123    fn sample(year: i32, month: u32, day: u32) -> DateTime<Utc> {
124        Utc.with_ymd_and_hms(year, month, day, 14, 5, 9).unwrap()
125    }
126
127    #[test]
128    fn formats_year_month_day_with_a_literal_separator() {
129        assert_eq!(format(sample(2026, 8, 17), "Y-m-d"), "2026-08-17");
130    }
131
132    #[test]
133    fn formats_full_month_name_and_ordinal_day() {
134        assert_eq!(format(sample(2026, 8, 1), "F jS, Y"), "August 1st, 2026");
135        assert_eq!(format(sample(2026, 8, 2), "F jS, Y"), "August 2nd, 2026");
136        assert_eq!(format(sample(2026, 8, 3), "F jS, Y"), "August 3rd, 2026");
137        assert_eq!(format(sample(2026, 8, 4), "F jS, Y"), "August 4th, 2026");
138        assert_eq!(format(sample(2026, 8, 11), "F jS, Y"), "August 11th, 2026");
139        assert_eq!(format(sample(2026, 8, 21), "F jS, Y"), "August 21st, 2026");
140    }
141
142    #[test]
143    fn formats_time_components() {
144        assert_eq!(format(sample(2026, 8, 17), "H:i:s"), "14:05:09");
145    }
146
147    #[test]
148    fn passes_through_characters_outside_the_recognized_set_literally() {
149        // Safe here only because the converter-time whitelist already
150        // rejected anything reaching this function with such a character -
151        // this just documents the fallback, not a claim of full coverage.
152        assert_eq!(format(sample(2026, 8, 17), "Q"), "Q");
153    }
154
155    #[test]
156    fn strtotime_parses_rfc3339() {
157        let parsed = strtotime("2026-08-17T14:05:09Z");
158        assert_eq!(format(parsed, "Y-m-d H:i:s"), "2026-08-17 14:05:09");
159    }
160
161    #[test]
162    fn strtotime_parses_the_eloquent_timestamp_format() {
163        let parsed = strtotime("2026-08-17 14:05:09");
164        assert_eq!(format(parsed, "Y-m-d H:i:s"), "2026-08-17 14:05:09");
165    }
166
167    #[test]
168    fn strtotime_parses_a_bare_date() {
169        let parsed = strtotime("2026-08-17");
170        assert_eq!(format(parsed, "Y-m-d H:i:s"), "2026-08-17 00:00:00");
171    }
172
173    #[test]
174    fn strtotime_falls_back_to_now_for_an_unrecognized_string() {
175        let before = Utc::now();
176        let parsed = strtotime("next monday");
177        assert!(parsed >= before);
178    }
179}