use jiff::{
SignedDuration, Timestamp, ZonedDateTime,
civil::{self, DateTime},
tz::{self, AmbiguousOffset, Disambiguation, Offset, TimeZone},
};
use std::{borrow::Cow, fmt};
pub(crate) const EPOCH: DateTime = civil::datetime(1970, 1, 1, 0, 0, 0, 0);
const ABBREVIATIONS: &[(&str, i32, bool)] = &[
("Z", 0, false),
("GMT", 0, false),
("EST", -18_000, false),
("EDT", -14_400, true),
("CST", -21_600, false),
("CDT", -18_000, true),
("MST", -25_200, false),
("MDT", -21_600, true),
("PST", -28_800, false),
("PDT", -25_200, true),
("AKST", -32_400, false),
("AKDT", -28_800, true),
("HST", -36_000, false),
("AST", -14_400, false),
("ADT", -10_800, true),
("NST", -12_600, false),
("NDT", -9_000, true),
("WET", 0, false),
("WEST", 3_600, true),
("BST", 3_600, true),
("CET", 3_600, false),
("CEST", 7_200, true),
("EET", 7_200, false),
("EEST", 10_800, true),
("SAST", 7_200, false),
("MSK", 10_800, false),
("HKT", 28_800, false),
("JST", 32_400, false),
("KST", 32_400, false),
("AWST", 28_800, false),
("ACST", 34_200, false),
("ACDT", 37_800, true),
("AEST", 36_000, false),
("AEDT", 39_600, true),
("NZST", 43_200, false),
("NZDT", 46_800, true),
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Zone {
Utc,
Offset(i32),
Abbreviation {
name: String,
offset: i32,
dst: bool,
},
Named(TimeZone),
}
impl Zone {
#[must_use]
pub fn parse(text: &str) -> Option<Self> {
let (zone, length) = Self::scan(text)?;
(length == text.len()).then_some(zone)
}
pub(crate) fn scan(text: &str) -> Option<(Self, usize)> {
let prefix = if text.starts_with("GMT+") || text.starts_with("GMT-") { 3 } else { 0 };
if let Some((offset, length)) = scan_offset(&text[prefix..]) {
return Some((Self::Offset(offset), prefix + length));
}
let length = text
.bytes()
.take_while(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'/' | b'+' | b'-'))
.count();
let word = &text[..length];
if word.is_empty() || not_an_identifier(word) {
return None;
}
if word.eq_ignore_ascii_case("UTC") {
return Some((Self::Utc, length));
}
if let Some(&(name, offset, dst)) = ABBREVIATIONS.iter().find(|(name, ..)| name.eq_ignore_ascii_case(word)) {
return Some((Self::Abbreviation { name: name.to_owned(), offset, dst }, length));
}
let zone = tz::db().get(word).ok()?;
zone.iana_name()?;
Some((Self::Named(zone), length))
}
fn time_zone(&self) -> Option<TimeZone> {
match self {
Self::Utc => Some(TimeZone::UTC),
Self::Offset(offset) | Self::Abbreviation { offset, .. } => {
Some(TimeZone::fixed(Offset::from_seconds(*offset).ok()?))
}
Self::Named(zone) => Some(zone.clone()),
}
}
}
fn not_an_identifier(word: &str) -> bool {
let lower = word.to_ascii_lowercase();
matches!(lower.as_str(), "posixrules" | "localtime" | "etc/unknown")
|| ["posix/", "right/", "systemv/"].iter().any(|prefix| lower.starts_with(prefix))
}
impl From<TimeZone> for Zone {
fn from(zone: TimeZone) -> Self {
if zone == TimeZone::UTC {
return Self::Utc;
}
if zone.iana_name().is_some() {
return Self::Named(zone);
}
match zone.to_fixed_offset() {
Ok(offset) => Self::Offset(offset.seconds()),
Err(_) => Self::Named(zone),
}
}
}
fn scan_offset(text: &str) -> Option<(i32, usize)> {
let sign = match text.as_bytes().first()? {
b'+' => 1,
b'-' => -1,
_ => return None,
};
let run = text[1..].bytes().take_while(|byte| byte.is_ascii_digit() || *byte == b':').count();
let body = &text[1..=run];
let number = |part: &str| {
(!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())).then(|| part.parse::<i32>().ok()).flatten()
};
let (hours, minutes, seconds) = match (body.len(), body.find(':')) {
(1 | 2, None) => (number(body)?, 0, 0),
(2, Some(1)) => (number(&body[..1])?, 0, 0),
(3, Some(2)) => (number(&body[..2])?, 0, 0),
(3, None) => (number(&body[..1])?, number(&body[1..])?, 0),
(3, Some(1)) => (number(&body[..1])?, number(&body[2..])?, 0),
(4, None) => (number(&body[..2])?, number(&body[2..])?, 0),
(4, Some(1)) => (number(&body[..1])?, number(&body[2..])?, 0),
(4, Some(2)) => (number(&body[..2])?, number(&body[3..])?, 0),
(5, Some(2)) => (number(&body[..2])?, number(&body[3..])?, 0),
(6, None) => (number(&body[..2])?, number(&body[2..4])?, number(&body[4..])?),
(8, Some(2)) if body.as_bytes()[5] == b':' => (number(&body[..2])?, number(&body[3..5])?, number(&body[6..])?),
_ => return None,
};
if minutes > 59 || seconds > 59 {
return None;
}
let offset = sign * (hours * 3600 + minutes * 60 + seconds);
Offset::from_seconds(offset).ok()?;
Some((offset, 1 + run))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhpDateTime {
local: DateTime,
zone: Zone,
offset: i32,
dst: bool,
abbreviation: Cow<'static, str>,
}
impl PhpDateTime {
pub fn new(local: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
Self::new_with(local, zone, Disambiguation::Compatible)
}
pub fn new_with(local: DateTime, zone: Zone, disambiguation: Disambiguation) -> Result<Self, jiff::Error> {
match &zone {
Zone::Utc => Ok(local.into()),
Zone::Offset(offset) => {
let offset = *offset;
Offset::from_seconds(offset)?;
let mut abbreviation = String::from("GMT");
let _ = write_offset(&mut abbreviation, offset, "");
Ok(Self { local, offset, dst: false, abbreviation: abbreviation.into(), zone })
}
Zone::Abbreviation { name, offset, dst } => {
Offset::from_seconds(*offset)?;
let (offset, dst, abbreviation) = (*offset, *dst, Cow::Owned(name.clone()));
Ok(Self { local, offset, dst, abbreviation, zone })
}
Zone::Named(tz) => {
let (local, offset) = resolve(tz, local, disambiguation)?;
let offset = offset.seconds();
let info = tz.to_offset_info(clamped_instant(local, offset));
let (dst, abbreviation) = (info.dst().is_dst(), Cow::Owned(info.abbreviation().to_owned()));
Ok(Self { local, offset, dst, abbreviation, zone })
}
}
}
pub fn from_utc(utc: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
if let Ok(instant) = TimeZone::UTC.to_timestamp(utc) {
return Self::from_timestamp(instant, zone);
}
let offset = match &zone {
Zone::Utc => 0,
Zone::Offset(offset) | Zone::Abbreviation { offset, .. } => Offset::from_seconds(*offset)?.seconds(),
Zone::Named(tz) => tz.to_offset(clamped_instant(utc, 0)).seconds(),
};
Self::new(utc.checked_add(SignedDuration::from_secs(i64::from(offset)))?, zone)
}
pub fn from_timestamp(timestamp: Timestamp, zone: Zone) -> Result<Self, jiff::Error> {
match &zone {
Zone::Named(tz) => Ok(Self::from_zoned(×tamp.to_zoned_datetime(tz.clone()), zone)),
Zone::Utc => Self::new(TimeZone::UTC.to_datetime(timestamp), zone),
Zone::Offset(offset) | Zone::Abbreviation { offset, .. } => {
let local = TimeZone::fixed(Offset::from_seconds(*offset)?).to_datetime(timestamp);
Self::new(local, zone)
}
}
}
fn from_zoned(date: &ZonedDateTime, zone: Zone) -> Self {
let info = date.time_zone().to_offset_info(date.timestamp());
Self {
local: date.datetime(),
zone,
offset: info.offset().seconds(),
dst: info.dst().is_dst(),
abbreviation: Cow::Owned(info.abbreviation().to_owned()),
}
}
pub fn in_zone(&self, zone: Zone) -> Result<Self, jiff::Error> {
Self::from_utc(self.local.checked_sub(SignedDuration::from_secs(i64::from(self.offset)))?, zone)
}
#[must_use]
pub const fn datetime(&self) -> &DateTime {
&self.local
}
#[must_use]
pub const fn zone(&self) -> &Zone {
&self.zone
}
#[must_use]
pub const fn offset_seconds(&self) -> i32 {
self.offset
}
#[must_use]
pub const fn is_dst(&self) -> bool {
self.dst
}
#[must_use]
pub fn abbreviation(&self) -> &str {
&self.abbreviation
}
pub fn to_timestamp(&self) -> Result<Timestamp, jiff::Error> {
Timestamp::from_duration(since_epoch(self.local, self.offset))
}
#[must_use]
pub fn timestamp(&self) -> i64 {
let since = since_epoch(self.local, self.offset);
since.as_secs() - i64::from(since.subsec_nanos() < 0)
}
pub fn to_zoned_datetime(&self) -> Result<ZonedDateTime, jiff::Error> {
let zone = self.zone.time_zone().ok_or_else(|| jiff::Error::from_args(format_args!("invalid offset")))?;
Ok(self.to_timestamp()?.to_zoned_datetime(zone))
}
}
fn since_epoch(local: DateTime, offset: i32) -> SignedDuration {
local.duration_since(EPOCH) - SignedDuration::from_secs(i64::from(offset))
}
fn clamped_instant(local: DateTime, offset: i32) -> Timestamp {
Timestamp::from_duration(since_epoch(local, offset)).unwrap_or(if local.year() < 0 {
Timestamp::MIN
} else {
Timestamp::MAX
})
}
fn resolve(
zone: &TimeZone,
local: DateTime,
disambiguation: Disambiguation,
) -> Result<(DateTime, Offset), jiff::Error> {
let rejected = |what| jiff::Error::from_args(format_args!("the local time {local} is {what} in this time zone"));
let gap = |before: Offset, after: Offset| SignedDuration::from_secs(i64::from(after.seconds() - before.seconds()));
Ok(match zone.to_ambiguous_timestamp(local).offset() {
AmbiguousOffset::Unambiguous { offset } => (local, offset),
AmbiguousOffset::Gap { before, after } => match disambiguation {
Disambiguation::Compatible | Disambiguation::Later => (local.checked_add(gap(before, after))?, after),
Disambiguation::Earlier => (local.checked_sub(gap(before, after))?, before),
_ => return Err(rejected("skipped")),
},
AmbiguousOffset::Fold { before, after } => match disambiguation {
Disambiguation::Compatible | Disambiguation::Earlier => (local, before),
Disambiguation::Later => (local, after),
_ => return Err(rejected("repeated")),
},
})
}
pub(crate) fn write_offset<W: fmt::Write + ?Sized>(out: &mut W, offset: i32, separator: &str) -> fmt::Result {
let sign = if offset < 0 { '-' } else { '+' };
let seconds = offset.unsigned_abs();
write!(out, "{sign}{:02}{separator}{:02}", seconds / 3600, seconds % 3600 / 60)
}
impl From<&Self> for PhpDateTime {
fn from(date: &Self) -> Self {
date.clone()
}
}
impl From<DateTime> for PhpDateTime {
fn from(local: DateTime) -> Self {
Self { local, zone: Zone::Utc, offset: 0, dst: false, abbreviation: Cow::Borrowed("UTC") }
}
}
impl From<&DateTime> for PhpDateTime {
fn from(local: &DateTime) -> Self {
(*local).into()
}
}
impl From<Timestamp> for PhpDateTime {
fn from(timestamp: Timestamp) -> Self {
TimeZone::UTC.to_datetime(timestamp).into()
}
}
impl From<ZonedDateTime> for PhpDateTime {
fn from(date: ZonedDateTime) -> Self {
Self::from_zoned(&date, date.time_zone().clone().into())
}
}