use jiff::{
SignedDuration, Timestamp, ZonedDateTime,
civil::DateTime,
tz::{self, Offset, TimeZone},
};
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 = ["GMT", "UTC"]
.iter()
.find(|prefix| text.get(..3).is_some_and(|head| head.eq_ignore_ascii_case(prefix)))
.map_or(0, |_| 3);
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() {
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()),
}
}
}
impl From<TimeZone> for Zone {
fn from(zone: TimeZone) -> Self {
if zone == TimeZone::UTC {
return Self::Utc;
}
match zone.iana_name() {
Some(_) => Self::Named(zone),
None => Self::Offset(zone.to_offset(Timestamp::UNIX_EPOCH).seconds()),
}
}
}
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),
(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: String,
}
impl PhpDateTime {
pub fn new(local: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
match &zone {
Zone::Utc => Ok(Self { local, offset: 0, dst: false, abbreviation: "UTC".into(), zone }),
Zone::Offset(offset) => {
let offset = *offset;
Offset::from_seconds(offset)?;
let abbreviation = format!("GMT{}", compact_offset(offset));
Ok(Self { local, offset, dst: false, abbreviation, zone })
}
Zone::Abbreviation { name, offset, dst } => {
Offset::from_seconds(*offset)?;
let (offset, dst, abbreviation) = (*offset, *dst, name.clone());
Ok(Self { local, offset, dst, abbreviation, zone })
}
Zone::Named(tz) => {
let zoned = tz.to_ambiguous_zoned_datetime(local).compatible()?;
Ok(Self::from_zoned(&zoned, zone))
}
}
}
pub fn from_utc(utc: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
let instant = TimeZone::UTC.to_timestamp(utc)?;
Self::from_timestamp(instant, 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: info.abbreviation().to_owned(),
}
}
pub fn in_zone(&self, zone: Zone) -> Result<Self, jiff::Error> {
Self::from_timestamp(self.to_timestamp()?, 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
}
pub fn to_timestamp(&self) -> Result<Timestamp, jiff::Error> {
TimeZone::UTC.to_timestamp(self.local)?.checked_sub(SignedDuration::from_secs(i64::from(self.offset)))
}
#[must_use]
pub fn timestamp(&self) -> i64 {
self.to_timestamp().map_or_else(
|_| if self.local.year() < 0 { Timestamp::MIN.as_second() } else { Timestamp::MAX.as_second() },
|timestamp| timestamp.as_second(),
)
}
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))
}
pub(crate) fn abbreviation(&self) -> &str {
&self.abbreviation
}
}
pub(crate) fn compact_offset(offset: i32) -> String {
let sign = if offset < 0 { '-' } else { '+' };
format!("{sign}{:02}{:02}", offset.abs() / 3600, offset.abs() % 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: "UTC".into() }
}
}
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())
}
}