1mod 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 pub fn utc() -> TzInfo {
58 TzInfo::get("UTC").unwrap_or_else(|| unreachable!("UTC is in the database"))
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum ErrorKind {
65 MalformedString,
67 InvalidTimeZone,
69 MalformedIntervalString,
71 Value,
73}
74
75#[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 pub fn kind(&self) -> ErrorKind {
91 self.kind
92 }
93
94 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 pub fn message_bytes(&self) -> &[u8] {
106 &self.message
107 }
108
109 pub fn message(&self) -> std::borrow::Cow<'_, str> {
111 String::from_utf8_lossy(&self.message)
112 }
113}
114
115impl fmt::Display for Error {
116 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
124fn c_str(s: &[u8]) -> &[u8] {
126 &s[..s.iter().position(|&c| c == 0).unwrap_or(s.len())]
127}
128
129fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct Timestamp {
147 pub sec: i64,
149 pub usec: i32,
151}
152
153impl Timestamp {
154 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
161pub fn time() -> i64 {
163 Timestamp::now().sec
164}
165
166pub fn microtime_float() -> f64 {
168 let t = Timestamp::now();
169 t.sec as f64 + f64::from(t.usec) / 1_000_000.0
170}
171
172pub fn microtime() -> String {
174 let t = Timestamp::now();
175 format!("{:.8} {}", f64::from(t.usec) / 1_000_000.0, t.sec)
176}
177
178#[derive(Debug, Clone, PartialEq)]
180pub enum TimeZone {
181 Offset(i64),
183 Abbr {
186 abbr: String,
188 utc_offset: i64,
190 dst: bool,
192 },
193 Id(TzInfo),
195}
196
197impl TimeZone {
198 pub fn utc() -> TimeZone {
200 TimeZone::Id(TzInfo::utc())
201 }
202
203 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 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 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 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
263fn 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#[derive(Debug, Clone)]
281pub struct DateTime {
282 t: Time,
283}
284
285impl DateTime {
286 pub fn new(time: &[u8], timezone: Option<&TimeZone>, default: &TzInfo) -> Result<DateTime, Error> {
288 DateTime::parse(time, timezone, default, Timestamp::now())
289 }
290
291 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 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 pub fn format(&self, format: &[u8]) -> Vec<u8> {
331 format::date_format(format, &self.t, self.t.is_localtime)
332 }
333
334 pub fn timestamp(&self) -> i64 {
336 self.t.sse
337 }
338
339 pub fn microsecond(&self) -> i64 {
341 self.t.us
342 }
343
344 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 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 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 pub fn modify(&mut self, modifier: &[u8]) -> Result<(), Error> {
388 modify(&mut self.t, modifier, "DateTime::modify(): ")
389 }
390
391 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 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 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 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 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 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 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 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 pub fn add(&mut self, interval: &Interval) {
464 self.t = self.t.add(&interval.0);
465 }
466
467 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 fn eq(&self, other: &Self) -> bool {
476 self.cmp_time(other) == Ordering::Equal
477 }
478}
479
480impl PartialOrd for DateTime {
481 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
483 Some(self.cmp_time(other))
484 }
485}
486
487impl DateTime {
488 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
511fn 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
529fn 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
577fn 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
584fn 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
594fn 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#[derive(Debug, Clone)]
655pub struct Modifier(Time);
656
657impl Modifier {
658 pub fn parse(modifier: &[u8]) -> Result<Modifier, Error> {
661 parse_modifier(modifier, "DateTimeImmutable::modify(): ").map(Modifier)
662 }
663}
664
665#[derive(Debug, Clone, PartialEq)]
667pub struct Interval(RelTime);
668
669impl Interval {
670 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
689pub 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
706pub 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
713pub 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#[derive(Debug, Clone, PartialEq)]
722pub struct ParsedDate {
723 time: Time,
724 messages: Messages,
725}
726
727pub fn date_parse(datetime: &[u8]) -> ParsedDate {
729 let (time, messages) = parse::strtotime(datetime);
730 ParsedDate { time, messages }
731}
732
733impl Messages {
734 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 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 pub fn messages(&self) -> &Messages {
763 &self.messages
764 }
765
766 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 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}