Skip to main content

php_std/
datetime.rs

1//! Date and time: date()/DateTime::format, DateTime parsing and timezones, strtotime, microtime.
2//!
3//! This is a port of timelib (the library inside `ext/date`) and of the
4//! parts of `php_date.c` around it, so that dates parse, normalise, convert
5//! between zones and format exactly as PHP 8.5 does, quirks included:
6//!
7//! | PHP | Rust |
8//! |---|---|
9//! | `new DateTime($s, $tz)` / `DateTimeImmutable` | [`DateTime::parse`] (explicit "now"), [`DateTime::new`] (system clock) |
10//! | `DateTime::createFromFormat($f, $s, $tz)` | [`DateTime::from_format`] |
11//! | `->format($f)`, `date($f, $ts)`, `gmdate($f, $ts)` | [`DateTime::format`], [`date`], [`gmdate`] |
12//! | `->modify($s)` | [`DateTime::modify`] (`DateTime`), [`DateTime::modified`] (`DateTimeImmutable`) |
13//! | `->setDate($y, $m, $d)` | [`DateTime::set_date`] (`DateTime`), [`DateTime::with_date`] (`DateTimeImmutable`) |
14//! | `->setTime($h, $i, $s, $us)` | [`DateTime::set_time`] (`DateTime`), [`DateTime::with_time`] (`DateTimeImmutable`) |
15//! | `->setTimezone($tz)`, `->getTimezone()` | [`DateTime::set_timezone`], [`DateTime::timezone`] |
16//! | `->getTimestamp()`, `->getOffset()`, `->getMicrosecond()` | [`DateTime::timestamp`], [`DateTime::offset`], [`DateTime::microsecond`] |
17//! | `->add(DateInterval::createFromDateString($s))` | [`DateTime::add`], [`Interval::from_date_string`] |
18//! | `$a < $b` | `PartialOrd` / `Ord` on [`DateTime`] |
19//! | `new DateTimeZone($name)`, `->getName()`, `->getOffset($dt)` | [`TimeZone::new`], [`TimeZone::name`], [`TimeZone::offset_at`] |
20//! | `strtotime($s, $base)` | [`strtotime`] |
21//! | `date_parse($s)` | [`date_parse`] ([`ParsedDate::to_php`]) |
22//! | `time()`, `microtime(true)`, `microtime()` | [`time`], [`microtime_float`], [`microtime`] |
23//! | `timezone_version_get()`, `timezone_identifiers_list()` | [`version`], [`identifiers`] |
24//!
25//! PHP keeps a default timezone in a global (`date.timezone`, UTC in
26//! Appwrite). Here it is an argument: functions that use it take a
27//! `default` [`TzInfo`] ([`TzInfo::utc`] for Appwrite).
28//!
29//! Timezone data is PHP's own bundled database (version [`version`]), not
30//! the system's, so results do not depend on the host.
31//!
32//! Not modelled: `DatePeriod`, `DateTime::diff()`, `DateTime::sub()`,
33//! intervals created from ISO 8601 durations, `setISODate`, `idate`,
34//! `mktime`, `strftime`, `getdate`, sunrise/sunset functions;
35//! `date_default_timezone_set` (pass the zone instead).
36
37mod abbreviations;
38mod format;
39mod from_format;
40mod parse;
41mod scanner;
42mod timelib;
43mod tz;
44mod tzindex;
45
46use std::cmp::Ordering;
47use std::fmt;
48
49use serde_json::{Map, Value};
50
51pub use parse::{Message, Messages};
52use timelib::{RelTime, Time, UNSET, ZONETYPE_ABBR, ZONETYPE_ID, ZONETYPE_OFFSET};
53pub use tz::{Abbreviation, TzInfo, abbreviations as abbreviation_list, identifiers, is_valid_id, version};
54
55impl TzInfo {
56    /// The `UTC` zone (Appwrite's default timezone).
57    pub fn utc() -> TzInfo {
58        TzInfo::get("UTC").unwrap_or_else(|| unreachable!("UTC is in the database"))
59    }
60}
61
62/// The PHP exception (or error) a date/time operation raises.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum ErrorKind {
65    /// `DateMalformedStringException`.
66    MalformedString,
67    /// `DateInvalidTimeZoneException`.
68    InvalidTimeZone,
69    /// `DateMalformedIntervalStringException`.
70    MalformedIntervalString,
71    /// `ValueError` (an argument PHP rejects, such as a NUL byte in a zone name).
72    Value,
73}
74
75/// Why a date/time operation failed: [`Error::php_class`] names the PHP
76/// exception, [`Error::message_bytes`] is its message byte for byte (PHP
77/// quotes the input verbatim, which need not be UTF-8).
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Error {
80    kind: ErrorKind,
81    message: Vec<u8>,
82}
83
84impl Error {
85    fn new(kind: ErrorKind, message: impl Into<Vec<u8>>) -> Error {
86        Error { kind, message: message.into() }
87    }
88
89    /// What went wrong, as an [`ErrorKind`].
90    pub fn kind(&self) -> ErrorKind {
91        self.kind
92    }
93
94    /// The PHP exception class.
95    pub fn php_class(&self) -> &'static str {
96        match self.kind {
97            ErrorKind::MalformedString => "DateMalformedStringException",
98            ErrorKind::InvalidTimeZone => "DateInvalidTimeZoneException",
99            ErrorKind::MalformedIntervalString => "DateMalformedIntervalStringException",
100            ErrorKind::Value => "ValueError",
101        }
102    }
103
104    /// The message, exactly.
105    pub fn message_bytes(&self) -> &[u8] {
106        &self.message
107    }
108
109    /// The message, with invalid UTF-8 replaced.
110    pub fn message(&self) -> std::borrow::Cow<'_, str> {
111        String::from_utf8_lossy(&self.message)
112    }
113}
114
115impl fmt::Display for Error {
116    /// Writes the message, with invalid UTF-8 replaced.
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str(&self.message())
119    }
120}
121
122impl std::error::Error for Error {}
123
124/// A C string (`%s`): the bytes up to the first NUL.
125fn c_str(s: &[u8]) -> &[u8] {
126    &s[..s.iter().position(|&c| c == 0).unwrap_or(s.len())]
127}
128
129/// `"{prefix}({input}) at position %d (%c): %s"` for the first error
130/// (`%c` of a NUL is a space).
131fn first_error(prefix: &str, input: &[u8], errors: &Messages) -> Vec<u8> {
132    let e = &errors.errors[0];
133    let mut out = Vec::with_capacity(prefix.len() + input.len() + 64);
134    out.extend_from_slice(prefix.as_bytes());
135    out.push(b'(');
136    out.extend_from_slice(c_str(input));
137    out.extend_from_slice(format!(") at position {} (", e.position).as_bytes());
138    out.push(if e.character == 0 { b' ' } else { e.character });
139    out.extend_from_slice(b"): ");
140    out.extend_from_slice(e.message.as_bytes());
141    out
142}
143
144/// A point in time, as `gettimeofday` reports it.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct Timestamp {
147    /// Seconds since the Unix epoch.
148    pub sec: i64,
149    /// Microseconds past `sec` (0 to 999 999).
150    pub usec: i32,
151}
152
153impl Timestamp {
154    /// The current time.
155    pub fn now() -> Timestamp {
156        let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
157        Timestamp { sec: d.as_secs() as i64, usec: d.subsec_micros() as i32 }
158    }
159}
160
161/// `time()`.
162pub fn time() -> i64 {
163    Timestamp::now().sec
164}
165
166/// `microtime(true)`: seconds since the epoch as a float.
167pub fn microtime_float() -> f64 {
168    let t = Timestamp::now();
169    t.sec as f64 + f64::from(t.usec) / 1_000_000.0
170}
171
172/// `microtime()`: `"0.12345600 1700000000"` (`%.8F %ld` of the fraction and the seconds).
173pub fn microtime() -> String {
174    let t = Timestamp::now();
175    format!("{:.8} {}", f64::from(t.usec) / 1_000_000.0, t.sec)
176}
177
178/// A timezone, as `DateTimeZone` holds it.
179#[derive(Debug, Clone, PartialEq)]
180pub enum TimeZone {
181    /// `timezone_type` 1: a fixed UTC offset in seconds (`+05:30`).
182    Offset(i64),
183    /// `timezone_type` 2: an abbreviation (`EST`), its UTC offset without
184    /// DST, and whether it is a DST abbreviation.
185    Abbr {
186        /// The abbreviation, as given.
187        abbr: String,
188        /// The UTC offset in seconds, without DST.
189        utc_offset: i64,
190        /// Whether it is a DST abbreviation.
191        dst: bool,
192    },
193    /// `timezone_type` 3: an identifier (`Europe/Paris`).
194    Id(TzInfo),
195}
196
197impl TimeZone {
198    /// `new DateTimeZone('UTC')`.
199    pub fn utc() -> TimeZone {
200        TimeZone::Id(TzInfo::utc())
201    }
202
203    /// `new DateTimeZone($timezone)`.
204    pub fn new(timezone: impl AsRef<[u8]>) -> Result<TimeZone, Error> {
205        let timezone = timezone.as_ref();
206        if timezone.contains(&0) {
207            return Err(Error::new(
208                ErrorKind::Value,
209                "DateTimeZone::__construct(): Argument #1 ($timezone) must not contain any null bytes",
210            ));
211        }
212        let fail = |what: &str| {
213            let mut m = format!("DateTimeZone::__construct(): {what} (").into_bytes();
214            m.extend_from_slice(timezone);
215            m.push(b')');
216            Err(Error::new(ErrorKind::InvalidTimeZone, m))
217        };
218        let mut t = Time::default();
219        let mut c = parse::Cursor { s: timezone, p: 0 };
220        let zone = parse::parse_zone(&mut c, &mut t);
221        let z = zone.offset as i32;
222        if i64::from(z) >= 100 * 3600 || i64::from(z) <= -100 * 3600 {
223            return fail("Timezone offset is out of range");
224        }
225        if zone.not_found || c.cur() != 0 {
226            return fail("Unknown or bad timezone");
227        }
228        Ok(match t.zone_type {
229            ZONETYPE_ID => TimeZone::Id(t.tz_info.unwrap_or_else(TzInfo::utc)),
230            ZONETYPE_OFFSET => TimeZone::Offset(i64::from(z)),
231            _ => TimeZone::Abbr { abbr: t.tz_abbr.unwrap_or_default(), utc_offset: i64::from(z), dst: t.dst != 0 },
232        })
233    }
234
235    /// `DateTimeZone::getName()`.
236    pub fn name(&self) -> String {
237        match self {
238            TimeZone::Id(tz) => tz.name().to_owned(),
239            TimeZone::Abbr { abbr, .. } => abbr.clone(),
240            TimeZone::Offset(offset) => offset_string(*offset),
241        }
242    }
243
244    /// The `timezone_type` PHP reports: 1 offset, 2 abbreviation, 3 identifier.
245    pub fn kind(&self) -> u32 {
246        match self {
247            TimeZone::Offset(_) => ZONETYPE_OFFSET,
248            TimeZone::Abbr { .. } => ZONETYPE_ABBR,
249            TimeZone::Id(_) => ZONETYPE_ID,
250        }
251    }
252
253    /// `DateTimeZone::getOffset($datetime)`: the UTC offset at `timestamp`.
254    pub fn offset_at(&self, timestamp: i64) -> i64 {
255        match self {
256            TimeZone::Id(tz) => i64::from(tz.info(timestamp).offset),
257            TimeZone::Offset(o) => *o,
258            TimeZone::Abbr { utc_offset, dst, .. } => utc_offset + i64::from(*dst) * 3600,
259        }
260    }
261}
262
263/// `date_create_tz_offset_str`: `+05:00`, or `+05:00:01` with seconds.
264fn offset_string(offset: i64) -> String {
265    let seconds = (offset % 60) as i32;
266    let sign = if offset < 0 { '-' } else { '+' };
267    let h = ((offset / 3600) as i32).unsigned_abs();
268    let m = (((offset % 3600) as i32) / 60).unsigned_abs();
269    if seconds == 0 {
270        format!("{sign}{h:02}:{m:02}")
271    } else {
272        format!("{sign}{h:02}:{m:02}:{:02}", seconds.unsigned_abs())
273    }
274}
275
276/// A `DateTime` (or `DateTimeImmutable`): a timelib time with its zone.
277///
278/// `==` and `<` compare instants, as PHP's do (`timelib_time_compare`): the
279/// same moment in two zones is equal.
280#[derive(Debug, Clone)]
281pub struct DateTime {
282    t: Time,
283}
284
285impl DateTime {
286    /// `new DateTime($time, $timezone)` at the current time.
287    pub fn new(time: &[u8], timezone: Option<&TimeZone>, default: &TzInfo) -> Result<DateTime, Error> {
288        DateTime::parse(time, timezone, default, Timestamp::now())
289    }
290
291    /// `new DateTime($time, $timezone)`, with "now" (which fills what the
292    /// string leaves out, and relative formats start from) given.
293    /// `default` is the zone PHP takes from `date.timezone`.
294    pub fn parse(
295        time: &[u8],
296        timezone: Option<&TimeZone>,
297        default: &TzInfo,
298        now: Timestamp,
299    ) -> Result<DateTime, Error> {
300        initialize(time, None, timezone, default, now).map(|t| DateTime { t })
301    }
302
303    /// `DateTime::createFromFormat($format, $time, $timezone)` with "now" given.
304    ///
305    /// `Ok(Err(messages))` where PHP returns `false` (`DateTime::getLastErrors()`
306    /// is [`Messages::to_php`] of them); `Err` where PHP throws (a NUL byte
307    /// in `time`). Without `!` or `|` in the format, fields the format does
308    /// not set come from `now`.
309    pub fn from_format(
310        format: &[u8],
311        time: &[u8],
312        timezone: Option<&TimeZone>,
313        default: &TzInfo,
314        now: Timestamp,
315    ) -> Result<Result<DateTime, Messages>, Error> {
316        if time.contains(&0) {
317            return Err(Error::new(
318                ErrorKind::Value,
319                "DateTime::createFromFormat(): Argument #2 ($datetime) must not contain any null bytes",
320            ));
321        }
322        let (t, errors) = from_format::parse_from_format(format, time);
323        if !errors.errors.is_empty() {
324            return Ok(Err(errors));
325        }
326        Ok(Ok(DateTime { t: finish(t, true, false, timezone, default, now) }))
327    }
328
329    /// `DateTime::format($format)` (bytes: PHP copies format bytes verbatim).
330    pub fn format(&self, format: &[u8]) -> Vec<u8> {
331        format::date_format(format, &self.t, self.t.is_localtime)
332    }
333
334    /// `DateTime::getTimestamp()`.
335    pub fn timestamp(&self) -> i64 {
336        self.t.sse
337    }
338
339    /// `DateTime::getMicrosecond()`.
340    pub fn microsecond(&self) -> i64 {
341        self.t.us
342    }
343
344    /// `DateTime::getOffset()`.
345    pub fn offset(&self) -> i64 {
346        if !self.t.is_localtime {
347            return 0;
348        }
349        match self.t.zone_type {
350            ZONETYPE_ID => self.t.tz_info.as_ref().map(|z| i64::from(z.info(self.t.sse).offset)).unwrap_or(0),
351            ZONETYPE_OFFSET => i64::from(self.t.z),
352            ZONETYPE_ABBR => i64::from(self.t.z) + 3600 * i64::from(self.t.dst),
353            _ => 0,
354        }
355    }
356
357    /// `DateTime::getTimezone()` (`None` where PHP returns `false`).
358    pub fn timezone(&self) -> Option<TimeZone> {
359        if !self.t.is_localtime {
360            return None;
361        }
362        Some(match self.t.zone_type {
363            ZONETYPE_ID => TimeZone::Id(self.t.tz_info.clone()?),
364            ZONETYPE_OFFSET => TimeZone::Offset(i64::from(self.t.z)),
365            _ => TimeZone::Abbr {
366                abbr: self.t.tz_abbr.clone().unwrap_or_default(),
367                utc_offset: i64::from(self.t.z),
368                dst: self.t.dst != 0,
369            },
370        })
371    }
372
373    /// `DateTime::setTimezone($timezone)`.
374    pub fn set_timezone(&mut self, timezone: &TimeZone) {
375        match timezone {
376            TimeZone::Offset(o) => self.t.set_timezone_from_offset(*o),
377            TimeZone::Abbr { abbr, utc_offset, dst } => {
378                self.t.set_timezone_from_abbr(abbr, *utc_offset, i32::from(*dst))
379            }
380            TimeZone::Id(tz) => self.t.set_timezone(tz),
381        }
382        let sse = self.t.sse;
383        self.t.unixtime2local(sse);
384    }
385
386    /// `DateTime::modify($modifier)` (mutable `DateTime`).
387    pub fn modify(&mut self, modifier: &[u8]) -> Result<(), Error> {
388        modify(&mut self.t, modifier, "DateTime::modify(): ")
389    }
390
391    /// `DateTimeImmutable::modify($modifier)`.
392    pub fn modified(&self, modifier: &[u8]) -> Result<DateTime, Error> {
393        let mut t = self.t.clone();
394        modify(&mut t, modifier, "DateTimeImmutable::modify(): ")?;
395        Ok(DateTime { t })
396    }
397
398    /// `DateTimeImmutable::modify($modifier)` with a [`Modifier`] parsed once.
399    pub fn modified_by(&self, modifier: &Modifier) -> DateTime {
400        let mut t = self.t.clone();
401        apply_modifier(&mut t, &modifier.0);
402        DateTime { t }
403    }
404
405    /// `(int) $date->format('w')`: the day of the week, 0 (Sunday) to 6.
406    pub fn day_of_week(&self) -> i64 {
407        i64::from(timelib::day_of_week(self.t.y, self.t.m, self.t.d) as i32)
408    }
409
410    /// `(int) $date->format('t')`: the number of days in the month.
411    pub fn days_in_month(&self) -> i64 {
412        i64::from(timelib::days_in_month(self.t.y, self.t.m) as i32)
413    }
414
415    /// Sets the year, month and day, keeping the time of day and the zone.
416    ///
417    /// Out-of-range values roll over (month 13 is January of the next
418    /// year, day 0 the last day of the previous month) and the timestamp is
419    /// recomputed. As in PHP, the fields are not re-derived from the new
420    /// timestamp, so a wall time that falls in a DST gap still formats as set.
421    ///
422    /// PHP: `DateTime::setDate()` / `DateTimeImmutable::setDate()`.
423    pub fn set_date(&mut self, year: i64, month: i64, day: i64) {
424        (self.t.y, self.t.m, self.t.d) = (year, month, day);
425        self.t.update_ts(None);
426    }
427
428    /// [`DateTime::set_date`] on a copy.
429    ///
430    /// PHP: `DateTimeImmutable::setDate()`.
431    pub fn with_date(&self, year: i64, month: i64, day: i64) -> DateTime {
432        let mut d = self.clone();
433        d.set_date(year, month, day);
434        d
435    }
436
437    /// Sets the hour, minute, second and microsecond, keeping the date and
438    /// the zone.
439    ///
440    /// Out-of-range values roll over into the next larger unit (hour 24 is
441    /// midnight of the next day), and the fields are then re-derived from
442    /// the new timestamp, so a wall time in a DST gap moves past it.
443    ///
444    /// PHP: `DateTime::setTime()` / `DateTimeImmutable::setTime()`
445    /// (`$second` and `$microsecond` default to 0 there).
446    pub fn set_time(&mut self, hour: i64, minute: i64, second: i64, microsecond: i64) {
447        (self.t.h, self.t.i, self.t.s, self.t.us) = (hour, minute, second, microsecond);
448        self.t.update_ts(None);
449        self.t.update_from_sse();
450    }
451
452    /// [`DateTime::set_time`] on a copy.
453    ///
454    /// PHP: `DateTimeImmutable::setTime()`.
455    pub fn with_time(&self, hour: i64, minute: i64, second: i64, microsecond: i64) -> DateTime {
456        let mut d = self.clone();
457        d.set_time(hour, minute, second, microsecond);
458        d
459    }
460
461    /// `DateTime::add($interval)` for an interval made by
462    /// `DateInterval::createFromDateString()`.
463    pub fn add(&mut self, interval: &Interval) {
464        self.t = self.t.add(&interval.0);
465    }
466
467    /// The broken-down fields (year, month, day, hour, minute, second).
468    pub fn fields(&self) -> (i64, i64, i64, i64, i64, i64) {
469        (self.t.y, self.t.m, self.t.d, self.t.h, self.t.i, self.t.s)
470    }
471}
472
473impl PartialEq for DateTime {
474    /// Whether both are the same instant, as PHP's `==` on `DateTime`.
475    fn eq(&self, other: &Self) -> bool {
476        self.cmp_time(other) == Ordering::Equal
477    }
478}
479
480impl PartialOrd for DateTime {
481    /// Orders by instant, as PHP's `<` and `>` on `DateTime`.
482    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
483        Some(self.cmp_time(other))
484    }
485}
486
487impl DateTime {
488    /// `timelib_time_compare` (what `<`, `>` and `==` on DateTime use).
489    pub fn cmp_time(&self, other: &DateTime) -> Ordering {
490        (self.t.sse, self.t.us).cmp(&(other.t.sse, other.t.us))
491    }
492}
493
494#[cfg(test)]
495mod equality_tests {
496    use super::*;
497
498    #[test]
499    fn the_same_instant_in_two_zones_is_equal() {
500        let utc = TzInfo::get("UTC").unwrap();
501        let now = Timestamp { sec: 1_700_000_000, usec: 0 };
502        let a = DateTime::parse(b"2024-01-01 12:00:00 UTC", None, &utc, now).unwrap();
503        let b = DateTime::parse(b"2024-01-01 14:00:00 +02:00", None, &utc, now).unwrap();
504        let c = DateTime::parse(b"2024-01-01 12:00:01 UTC", None, &utc, now).unwrap();
505        assert!(a == b);
506        assert_eq!(a.partial_cmp(&b), Some(Ordering::Equal));
507        assert!(a != c && a < c);
508    }
509}
510
511/// `php_date_initialize` for a free-form string.
512fn initialize(
513    time: &[u8],
514    format: Option<&[u8]>,
515    timezone: Option<&TimeZone>,
516    default: &TzInfo,
517    now: Timestamp,
518) -> Result<Time, Error> {
519    let _ = format;
520    let time: &[u8] = if time.is_empty() { b"now" } else { time };
521    let (t, errors) = parse::strtotime(time);
522    if !errors.errors.is_empty() {
523        return Err(Error::new(ErrorKind::MalformedString, first_error("Failed to parse time string ", time, &errors)));
524    }
525    let is_now = time == b"now";
526    Ok(finish(t, false, is_now, timezone, default, now))
527}
528
529/// The rest of `php_date_initialize`: the zone, "now", `timelib_fill_holes`,
530/// `timelib_update_ts` and `timelib_update_from_sse`.
531fn finish(
532    mut t: Time,
533    from_format: bool,
534    is_now: bool,
535    timezone: Option<&TimeZone>,
536    default: &TzInfo,
537    now: Timestamp,
538) -> Time {
539    let mut now_t = Time::default();
540    let tzi: Option<TzInfo> = match timezone {
541        Some(TimeZone::Id(tz)) => {
542            now_t.zone_type = ZONETYPE_ID;
543            now_t.tz_info = Some(tz.clone());
544            Some(tz.clone())
545        }
546        Some(TimeZone::Offset(o)) => {
547            now_t.zone_type = ZONETYPE_OFFSET;
548            now_t.z = *o as i32;
549            None
550        }
551        Some(TimeZone::Abbr { abbr, utc_offset, dst }) => {
552            now_t.zone_type = ZONETYPE_ABBR;
553            now_t.z = *utc_offset as i32;
554            now_t.dst = i32::from(*dst);
555            now_t.tz_abbr = Some(abbr.clone());
556            None
557        }
558        None => {
559            let tz = t.tz_info.clone().unwrap_or_else(|| default.clone());
560            now_t.zone_type = ZONETYPE_ID;
561            now_t.tz_info = Some(tz.clone());
562            Some(tz)
563        }
564    };
565    now_t.unixtime2local(now.sec);
566    now_t.us = i64::from(now.usec);
567    if !from_format && is_now {
568        return now_t;
569    }
570    t.fill_holes(&now_t, from_format);
571    t.update_ts(tzi.as_ref());
572    t.update_from_sse();
573    t.have_relative = false;
574    t
575}
576
577/// `php_date_modify`.
578fn modify(t: &mut Time, modifier: &[u8], prefix: &str) -> Result<(), Error> {
579    let tmp = parse_modifier(modifier, prefix)?;
580    apply_modifier(t, &tmp);
581    Ok(())
582}
583
584/// The parse half of `php_date_modify`.
585fn parse_modifier(modifier: &[u8], prefix: &str) -> Result<Time, Error> {
586    let (tmp, errors) = parse::strtotime(modifier);
587    if !errors.errors.is_empty() {
588        let message = first_error(&format!("{prefix}Failed to parse time string "), modifier, &errors);
589        return Err(Error::new(ErrorKind::MalformedString, message));
590    }
591    Ok(tmp)
592}
593
594/// The apply half of `php_date_modify`: `tmp` is a parsed modifier.
595fn apply_modifier(t: &mut Time, tmp: &Time) {
596    t.relative = tmp.relative.clone();
597    t.have_relative = tmp.have_relative;
598    t.sse_uptodate = false;
599    if tmp.y != UNSET {
600        t.y = tmp.y;
601    }
602    if tmp.m != UNSET {
603        t.m = tmp.m;
604    }
605    if tmp.d != UNSET {
606        t.d = tmp.d;
607    }
608    if tmp.h != UNSET {
609        t.h = tmp.h;
610        if tmp.i != UNSET {
611            t.i = tmp.i;
612            t.s = if tmp.s != UNSET { tmp.s } else { 0 };
613        } else {
614            t.i = 0;
615            t.s = 0;
616        }
617    }
618    if tmp.us != UNSET {
619        t.us = tmp.us;
620    }
621    if tmp.y == 1970
622        && tmp.m == 1
623        && tmp.d == 1
624        && tmp.h == 0
625        && tmp.i == 0
626        && tmp.s == 0
627        && tmp.us == 0
628        && tmp.have_zone != 0
629        && tmp.zone_type == ZONETYPE_OFFSET
630        && tmp.z == 0
631        && tmp.dst == 0
632    {
633        t.set_timezone_from_offset(0);
634    }
635    t.update_ts(None);
636    t.update_from_sse();
637    t.have_relative = false;
638    t.relative = RelTime::default();
639}
640
641/// A modifier string parsed once, to apply to many dates: what
642/// `DateTimeImmutable::modify($modifier)` does, without parsing the string
643/// again each time.
644///
645/// ```
646/// use php_std::datetime::{DateTime, Modifier, Timestamp, TzInfo};
647///
648/// let next_day = Modifier::parse(b"+1 day")?;
649/// let at = DateTime::parse(b"2026-03-28 12:00", Some(&php_std::datetime::TimeZone::new("Europe/Paris")?), &TzInfo::utc(), Timestamp { sec: 0, usec: 0 })?;
650/// assert_eq!(at.modified_by(&next_day).format(b"Y-m-d H:i T"), b"2026-03-29 12:00 CEST");
651/// assert_eq!(at.modified_by(&next_day), at.modified(b"+1 day")?);
652/// # Ok::<(), php_std::datetime::Error>(())
653/// ```
654#[derive(Debug, Clone)]
655pub struct Modifier(Time);
656
657impl Modifier {
658    /// Parses `modifier` as `DateTimeImmutable::modify()` does, failing with
659    /// the same error.
660    pub fn parse(modifier: &[u8]) -> Result<Modifier, Error> {
661        parse_modifier(modifier, "DateTimeImmutable::modify(): ").map(Modifier)
662    }
663}
664
665/// A `DateInterval` made by `DateInterval::createFromDateString()`.
666#[derive(Debug, Clone, PartialEq)]
667pub struct Interval(RelTime);
668
669impl Interval {
670    /// `DateInterval::createFromDateString($datetime)`.
671    pub fn from_date_string(datetime: &[u8]) -> Result<Interval, Error> {
672        let (t, errors) = parse::strtotime(datetime);
673        if !errors.errors.is_empty() {
674            return Err(Error::new(
675                ErrorKind::MalformedIntervalString,
676                first_error("Unknown or bad format ", datetime, &errors),
677            ));
678        }
679        if t.have_date != 0 || t.have_time != 0 || t.have_zone != 0 {
680            let mut m = b"String '".to_vec();
681            m.extend_from_slice(c_str(datetime));
682            m.extend_from_slice(b"' contains non-relative elements");
683            return Err(Error::new(ErrorKind::MalformedIntervalString, m));
684        }
685        Ok(Interval(t.relative))
686    }
687}
688
689/// `strtotime($datetime, $baseTimestamp)` in the default zone: `None` where
690/// PHP returns `false`.
691pub fn strtotime(datetime: &[u8], base: i64, default: &TzInfo) -> Option<i64> {
692    if datetime.is_empty() {
693        return None;
694    }
695    let mut now = Time { tz_info: Some(default.clone()), zone_type: ZONETYPE_ID, ..Time::default() };
696    now.unixtime2local(base);
697    let (mut t, errors) = parse::strtotime(datetime);
698    if !errors.errors.is_empty() {
699        return None;
700    }
701    t.fill_holes(&now, false);
702    t.update_ts(Some(default));
703    Some(t.sse)
704}
705
706/// `date($format, $timestamp)` in the default zone.
707pub fn date(format: &[u8], timestamp: i64, default: &TzInfo) -> Vec<u8> {
708    let mut t = Time { tz_info: Some(default.clone()), zone_type: ZONETYPE_ID, ..Time::default() };
709    t.unixtime2local(timestamp);
710    format::date_format(format, &t, true)
711}
712
713/// `gmdate($format, $timestamp)`.
714pub fn gmdate(format: &[u8], timestamp: i64) -> Vec<u8> {
715    let mut t = Time::default();
716    t.unixtime2gmt(timestamp);
717    format::date_format(format, &t, false)
718}
719
720/// What `date_parse()` returns.
721#[derive(Debug, Clone, PartialEq)]
722pub struct ParsedDate {
723    time: Time,
724    messages: Messages,
725}
726
727/// `date_parse($datetime)`.
728pub fn date_parse(datetime: &[u8]) -> ParsedDate {
729    let (time, messages) = parse::strtotime(datetime);
730    ParsedDate { time, messages }
731}
732
733impl Messages {
734    /// The array `DateTime::getLastErrors()` returns:
735    /// `warning_count`, `warnings`, `error_count`, `errors`, messages keyed by
736    /// position (a later message at the same position replaces an earlier one).
737    pub fn to_php(&self) -> Value {
738        let mut m = Map::new();
739        self.insert_into(&mut m);
740        Value::Object(m)
741    }
742
743    fn insert_into(&self, m: &mut Map<String, Value>) {
744        let by_position = |list: &[Message]| {
745            let mut a = Map::new();
746            for msg in list {
747                a.insert(msg.position.to_string(), Value::String(msg.message.into()));
748            }
749            // Positions are integer keys: keys 0..n-1 in order make a list.
750            let is_list = a.keys().enumerate().all(|(i, k)| *k == i.to_string());
751            if is_list { Value::Array(a.into_iter().map(|(_, v)| v).collect()) } else { Value::Object(a) }
752        };
753        m.insert("warning_count".into(), Value::from(self.warnings.len()));
754        m.insert("warnings".into(), by_position(&self.warnings));
755        m.insert("error_count".into(), Value::from(self.errors.len()));
756        m.insert("errors".into(), by_position(&self.errors));
757    }
758}
759
760impl ParsedDate {
761    /// The errors and warnings.
762    pub fn messages(&self) -> &Messages {
763        &self.messages
764    }
765
766    /// The array PHP returns (`php_date_do_return_parsed_time`), in the
767    /// request model: unset fields are `false`, warnings and errors are keyed
768    /// by position (a later message at the same position replaces an
769    /// earlier one).
770    pub fn to_php(&self) -> Value {
771        let t = &self.time;
772        let mut m = Map::new();
773        let field = |v: i64| if v == UNSET { Value::Bool(false) } else { Value::from(v) };
774        m.insert("year".into(), field(t.y));
775        m.insert("month".into(), field(t.m));
776        m.insert("day".into(), field(t.d));
777        m.insert("hour".into(), field(t.h));
778        m.insert("minute".into(), field(t.i));
779        m.insert("second".into(), field(t.s));
780        m.insert(
781            "fraction".into(),
782            if t.us == UNSET {
783                Value::Bool(false)
784            } else {
785                serde_json::Number::from_f64(t.us as f64 / 1_000_000.0).map(Value::Number).unwrap_or(Value::Null)
786            },
787        );
788        self.messages.insert_into(&mut m);
789        m.insert("is_localtime".into(), Value::Bool(t.is_localtime));
790        if t.is_localtime {
791            m.insert("zone_type".into(), field(i64::from(t.zone_type)));
792            match t.zone_type {
793                ZONETYPE_OFFSET => {
794                    m.insert("zone".into(), field(i64::from(t.z)));
795                    m.insert("is_dst".into(), Value::Bool(t.dst != 0));
796                }
797                ZONETYPE_ID => {
798                    if let Some(a) = &t.tz_abbr {
799                        m.insert("tz_abbr".into(), Value::String(a.clone()));
800                    }
801                    if let Some(tz) = &t.tz_info {
802                        m.insert("tz_id".into(), Value::String(tz.name().to_owned()));
803                    }
804                }
805                ZONETYPE_ABBR => {
806                    m.insert("zone".into(), field(i64::from(t.z)));
807                    m.insert("is_dst".into(), Value::Bool(t.dst != 0));
808                    m.insert("tz_abbr".into(), Value::String(t.tz_abbr.clone().unwrap_or_default()));
809                }
810                _ => {}
811            }
812        }
813        if t.have_relative {
814            let r = &t.relative;
815            let mut rel = Map::new();
816            rel.insert("year".into(), Value::from(r.y));
817            rel.insert("month".into(), Value::from(r.m));
818            rel.insert("day".into(), Value::from(r.d));
819            rel.insert("hour".into(), Value::from(r.h));
820            rel.insert("minute".into(), Value::from(r.i));
821            rel.insert("second".into(), Value::from(r.s));
822            if r.have_weekday_relative {
823                rel.insert("weekday".into(), Value::from(r.weekday));
824            }
825            if r.have_special_relative && r.special_type == timelib::SPECIAL_WEEKDAY {
826                rel.insert("weekdays".into(), Value::from(r.special_amount));
827            }
828            if r.first_last_day_of != 0 {
829                let key = if r.first_last_day_of == timelib::FIRST_DAY_OF_MONTH {
830                    "first_day_of_month"
831                } else {
832                    "last_day_of_month"
833                };
834                rel.insert(key.into(), Value::Bool(true));
835            }
836            m.insert("relative".into(), Value::Object(rel));
837        }
838        Value::Object(m)
839    }
840}
841
842#[cfg(test)]
843mod tests {
844    use super::*;
845
846    const NOW: Timestamp = Timestamp { sec: 1791544240, usec: 227884 };
847
848    fn dt(s: &str) -> DateTime {
849        DateTime::parse(s.as_bytes(), None, &TzInfo::utc(), NOW).unwrap()
850    }
851
852    fn fmt(d: &DateTime, f: &str) -> String {
853        String::from_utf8(d.format(f.as_bytes())).unwrap()
854    }
855
856    #[test]
857    fn database_formats() {
858        let d = dt("2024-07-01 12:00:00.123");
859        assert_eq!(fmt(&d, "Y-m-d H:i:s.v"), "2024-07-01 12:00:00.123");
860        assert_eq!(fmt(&d, "Y-m-d\\TH:i:s.vP"), "2024-07-01T12:00:00.123+00:00");
861        let d = dt("2024-07-01T12:00:00.5+05:30");
862        assert_eq!(fmt(&d, "c e T U"), "2024-07-01T12:00:00+05:30 +05:30 GMT+0530 1719815400");
863    }
864
865    #[test]
866    fn relative_formats() {
867        // NOW is 2026-10-09 11:10:40 UTC.
868        assert_eq!(fmt(&dt("tomorrow noon"), "Y-m-d H:i:s"), "2026-10-10 12:00:00");
869        assert_eq!(fmt(&dt("next monday"), "Y-m-d H:i:s"), "2026-10-12 00:00:00");
870        assert_eq!(fmt(&dt("last day of next month"), "Y-m-d"), "2026-11-30");
871        assert_eq!(fmt(&dt("first monday of january 2024"), "Y-m-d H:i"), "2024-01-01 00:00");
872        assert_eq!(fmt(&dt("2021-02-30"), "Y-m-d"), "2021-03-02");
873    }
874
875    #[test]
876    fn zones() {
877        let paris = TimeZone::new("europe/paris").unwrap();
878        assert_eq!(paris.name(), "europe/paris");
879        let d = DateTime::parse(b"2024-07-01 12:00:00", Some(&paris), &TzInfo::utc(), NOW).unwrap();
880        assert_eq!(fmt(&d, "e T P O p Z I U"), "europe/paris CEST +02:00 +0200 +02:00 7200 1 1719828000");
881        assert_eq!(TimeZone::new("+100:00").unwrap().name(), "+00:01");
882        assert_eq!(TimeZone::new("utc").unwrap().name(), "UTC");
883        assert_eq!(
884            TimeZone::new("xyz").unwrap_err().message(),
885            "DateTimeZone::__construct(): Unknown or bad timezone (xyz)"
886        );
887    }
888
889    #[test]
890    fn errors() {
891        let e = DateTime::parse(b"now foo", None, &TzInfo::utc(), NOW).unwrap_err();
892        assert_eq!(
893            e.message(),
894            "Failed to parse time string (now foo) at position 4 (f): The timezone could not be found in the database"
895        );
896        let mut d = dt("2024-01-01");
897        assert_eq!(
898            d.modify(b"").unwrap_err().message(),
899            "DateTime::modify(): Failed to parse time string () at position 0 ( ): Empty string"
900        );
901    }
902
903    #[test]
904    fn date_and_strtotime() {
905        assert_eq!(gmdate(b"\\", 0), vec![0]);
906        assert_eq!(date(b"D, d M Y H:i:s", -62167219200 * 2, &TzInfo::utc()), b"Mon, 31 Dec -1971 00:00:00".to_vec());
907        assert_eq!(strtotime(b"1 January 1970 00:00:00 UTC", 0, &TzInfo::utc()), Some(0));
908        assert_eq!(strtotime(b"foo", 0, &TzInfo::utc()), None);
909    }
910}