Skip to main content

sql_values/
datetime.rs

1//! PostgreSQL 18's `date`, `time`, `timetz`, `timestamp` and `timestamptz`, held as PostgreSQL
2//! stores them, printed by their output functions under `DateStyle` `ISO`, and converted into one
3//! another in a [`PgTimeZone`].
4
5mod input;
6#[cfg(feature = "jiff")]
7mod jiff_conversions;
8
9use core::{cmp::Ordering, fmt};
10
11pub use input::{InputContext, parse_date, parse_time, parse_timestamp, parse_timestamp_tz};
12
13use crate::PgTimeZone;
14
15pub(crate) const USECS_PER_SEC: i64 = 1_000_000;
16pub(crate) const USECS_PER_MINUTE: i64 = 60_000_000;
17pub(crate) const USECS_PER_HOUR: i64 = 3_600_000_000;
18pub(crate) const USECS_PER_DAY: i64 = 86_400_000_000;
19pub(crate) const MONTHS_PER_YEAR: i32 = 12;
20/// `POSTGRES_EPOCH_JDATE`, the Julian day of 2000-01-01.
21pub(crate) const POSTGRES_EPOCH_JDATE: i32 = 2_451_545;
22/// Seconds from 1970-01-01, `UNIX_EPOCH_JDATE`, to 2000-01-01.
23const UNIX_TO_POSTGRES_SECS: i64 = 946_684_800;
24/// `DATE_END_JULIAN`, the Julian day of 5874898-01-01, past the last date.
25const DATE_END_JULIAN: i32 = 2_147_483_494;
26/// `MIN_TIMESTAMP`, 4714-11-24 00:00:00 BC.
27pub(crate) const MIN_TIMESTAMP: i64 = -211_813_488_000_000_000;
28/// `END_TIMESTAMP`, 294277-01-01 00:00:00, past the last timestamp.
29pub(crate) const END_TIMESTAMP: i64 = 9_223_371_331_200_000_000;
30/// `TZDISP_LIMIT`, the largest offset a `timetz` holds, in seconds.
31const TZDISP_LIMIT: i32 = 16 * 3_600;
32
33/// Why PostgreSQL refuses a date or time, one variant per message it raises, or why this crate
34/// declines to answer for it.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
36pub enum DateTimeError {
37    /// A year, month, day, hour, minute or second no calendar or clock has.
38    #[error("date/time field value out of range")]
39    FieldValueOutOfRange,
40    /// An offset of 16 hours or more, or with minutes or seconds of 60 or more.
41    #[error("time zone displacement out of range")]
42    TimeZoneDisplacementOutOfRange,
43    /// A date before 4714-11-24 BC or from 5874898-01-01.
44    #[error("date out of range")]
45    DateOutOfRange,
46    /// A timestamp before 4714-11-24 BC or from 294277-01-01.
47    #[error("timestamp out of range")]
48    TimestampOutOfRange,
49    /// A value outside jiff's years -9999 to 9999, an infinity included, where jiff's types or
50    /// its time zone database are needed.
51    #[error("value outside jiff's years -9999 to 9999")]
52    OutsideJiffRange,
53    /// A literal without an offset read as a `timestamptz` with no time zone in the
54    /// [`InputContext`].
55    #[error("the literal needs a time zone to read as timestamp with time zone")]
56    NeedsTimeZone,
57    /// An abbreviation whose set names a zone that does not exist.
58    #[error("time zone not recognized")]
59    TimeZoneNotRecognized,
60    /// A spelling this crate does not model. The readers take the ISO spelling
61    /// `YYYY-MM-DD[( |T)HH:MM[:SS[.f]][offset]]` that no `DateStyle` changes, followed by a zone
62    /// abbreviation or all-letter zone name and ` BC` or ` AD`, and the special words that need
63    /// no clock.
64    #[error("date/time spelling not modelled")]
65    Unsupported,
66}
67
68/// A PostgreSQL `date`, days from 2000-01-01, from 4714-11-24 BC to 5874897-12-31 and the two
69/// infinities, ordered as PostgreSQL orders it.
70///
71/// ```
72/// use sql_values::{InputContext, PgDate};
73///
74/// let leap = PgDate::from_ymd(2024, 2, 29).unwrap();
75/// assert_eq!(leap.to_string(), "2024-02-29");
76/// assert_eq!(PgDate::parse("2024-02-29", InputContext::new()), Ok(leap));
77/// assert_eq!(PgDate::from_ymd(-4713, 11, 24).unwrap().to_string(), "4714-11-24 BC");
78/// assert!(PgDate::from_ymd(-4713, 11, 23).is_none());
79/// assert!(PgDate::NEG_INFINITY < leap && leap < PgDate::INFINITY);
80/// ```
81#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
82#[cfg_attr(
83    feature = "serde",
84    derive(serde::Serialize, serde::Deserialize),
85    serde(try_from = "i32", into = "i32")
86)]
87pub struct PgDate(i32);
88
89/// A PostgreSQL `time`, microseconds from midnight to 24:00:00 inclusive.
90///
91/// ```
92/// use sql_values::PgTime;
93///
94/// let noon = PgTime::from_hms_micro(12, 0, 0, 500_000).unwrap();
95/// assert_eq!(noon.to_string(), "12:00:00.5");
96/// assert_eq!(PgTime::from_micros(86_400_000_000).unwrap().to_string(), "24:00:00");
97/// ```
98#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
99#[cfg_attr(
100    feature = "serde",
101    derive(serde::Serialize, serde::Deserialize),
102    serde(try_from = "i64", into = "i64")
103)]
104pub struct PgTime(i64);
105
106/// A PostgreSQL `timetz`, a time of day with the offset east of UTC it was written with,
107/// ordered by the instant and then by the offset, as `timetz_cmp` orders it.
108///
109/// ```
110/// use sql_values::{PgTime, PgTimeTz};
111///
112/// let noon = PgTime::from_hms_micro(12, 0, 0, 0).unwrap();
113/// let rome = PgTimeTz::new(noon, 3_600).unwrap();
114/// assert_eq!(rome.to_string(), "12:00:00+01");
115/// let utc = PgTimeTz::new(PgTime::from_hms_micro(11, 0, 0, 0).unwrap(), 0).unwrap();
116/// // At one instant the offset decides, by PostgreSQL's zone in seconds west of UTC.
117/// assert_ne!(rome, utc);
118/// assert!(rome < utc);
119/// ```
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
122#[cfg_attr(feature = "serde", serde(try_from = "(i64, i32)", into = "(i64, i32)"))]
123pub struct PgTimeTz {
124    time: i64,
125    offset: i32,
126}
127
128/// A PostgreSQL `timestamp`, microseconds from 2000-01-01 00:00:00, from 4714-11-24 BC to
129/// 294276-12-31 23:59:59.999999 and the two infinities.
130///
131/// ```
132/// use sql_values::{InputContext, PgTimestamp};
133///
134/// let last = PgTimestamp::parse("294276-12-31 23:59:59.999999", InputContext::new()).unwrap();
135/// assert_eq!(last.to_string(), "294276-12-31 23:59:59.999999");
136/// assert_eq!(PgTimestamp::INFINITY.to_string(), "infinity");
137/// assert!(last < PgTimestamp::INFINITY);
138/// ```
139#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
140#[cfg_attr(
141    feature = "serde",
142    derive(serde::Serialize, serde::Deserialize),
143    serde(try_from = "i64", into = "i64")
144)]
145pub struct PgTimestamp(i64);
146
147/// A PostgreSQL `timestamptz`, the instant as microseconds from 2000-01-01 00:00:00 UTC, over the
148/// range of [`PgTimestamp`], printed as under `TimeZone` `UTC`.
149///
150/// ```
151/// use sql_values::{InputContext, PgTimestampTz};
152///
153/// let at = PgTimestampTz::parse("2026-03-29 12:00:00+02", InputContext::new()).unwrap();
154/// assert_eq!(at.to_string(), "2026-03-29 10:00:00+00");
155/// ```
156#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
157#[cfg_attr(
158    feature = "serde",
159    derive(serde::Serialize, serde::Deserialize),
160    serde(try_from = "i64", into = "i64")
161)]
162pub struct PgTimestampTz(i64);
163
164impl PgDate {
165    /// `infinity`, PostgreSQL's `DATEVAL_NOEND`, after every date.
166    pub const INFINITY: Self = Self(i32::MAX);
167    /// `-infinity`, PostgreSQL's `DATEVAL_NOBEGIN`, before every date.
168    pub const NEG_INFINITY: Self = Self(i32::MIN);
169
170    /// The date of the proleptic Gregorian `year`, `month` and `day`, where year `Y` BC is year
171    /// `1 - Y`, or `None` outside the calendar or PostgreSQL's dates.
172    #[must_use]
173    pub fn from_ymd(year: i32, month: u8, day: u8) -> Option<Self> {
174        let (month, day) = (i32::from(month), i32::from(day));
175        if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
176            return None;
177        }
178        if !is_valid_julian(year, month) {
179            return None;
180        }
181        Self::from_pg_days(date2j(year, month, day) - POSTGRES_EPOCH_JDATE)
182    }
183
184    /// The date `days` after 2000-01-01, as PostgreSQL stores it, where `i32::MAX` and `i32::MIN`
185    /// are the infinities, or `None` outside PostgreSQL's dates.
186    #[must_use]
187    pub const fn from_pg_days(days: i32) -> Option<Self> {
188        let valid = -POSTGRES_EPOCH_JDATE <= days && days < DATE_END_JULIAN - POSTGRES_EPOCH_JDATE;
189        if valid || days == i32::MAX || days == i32::MIN {
190            Some(Self(days))
191        } else {
192            None
193        }
194    }
195
196    /// Days from 2000-01-01, as PostgreSQL stores the date.
197    #[must_use]
198    pub const fn pg_days(self) -> i32 {
199        self.0
200    }
201
202    /// Whether the date is neither `infinity` nor `-infinity`.
203    #[must_use]
204    pub const fn is_finite(self) -> bool {
205        self.0 != i32::MAX && self.0 != i32::MIN
206    }
207
208    /// The year, month and day, where year `Y` BC is year `1 - Y`, or `None` for an infinity.
209    ///
210    /// ```
211    /// use sql_values::PgDate;
212    ///
213    /// assert_eq!(PgDate::from_pg_days(0).unwrap().ymd(), Some((2000, 1, 1)));
214    /// assert_eq!(PgDate::INFINITY.ymd(), None);
215    /// ```
216    #[must_use]
217    pub fn ymd(self) -> Option<(i32, u8, u8)> {
218        self.is_finite().then(|| {
219            let (year, month, day) = j2date(self.0 + POSTGRES_EPOCH_JDATE);
220            (year, narrow_u8(month.into()), narrow_u8(day.into()))
221        })
222    }
223}
224
225impl PgTime {
226    /// Midnight, `00:00:00`.
227    pub const MIDNIGHT: Self = Self(0);
228
229    /// The time `micros` microseconds after midnight, or `None` outside 00:00:00 to 24:00:00.
230    #[must_use]
231    pub const fn from_micros(micros: i64) -> Option<Self> {
232        if 0 <= micros && micros <= USECS_PER_DAY {
233            Some(Self(micros))
234        } else {
235            None
236        }
237    }
238
239    /// The time of `hour`, `minute`, `second` and `microsecond`, or `None` past 24:00:00 or
240    /// with a field beyond its clock.
241    #[must_use]
242    pub fn from_hms_micro(hour: u8, minute: u8, second: u8, microsecond: u32) -> Option<Self> {
243        if hour > 24 || minute > 59 || second > 59 || microsecond > 999_999 {
244            return None;
245        }
246        Self::from_micros(
247            i64::from(hour) * USECS_PER_HOUR
248                + i64::from(minute) * USECS_PER_MINUTE
249                + i64::from(second) * USECS_PER_SEC
250                + i64::from(microsecond),
251        )
252    }
253
254    /// Microseconds after midnight, as PostgreSQL stores the time.
255    #[must_use]
256    pub const fn micros(self) -> i64 {
257        self.0
258    }
259
260    /// The hour, minute, second and microsecond, where 24:00:00 is hour 24.
261    ///
262    /// ```
263    /// use sql_values::PgTime;
264    ///
265    /// let t = PgTime::from_micros(45_296_000_007).unwrap();
266    /// assert_eq!(t.hms_micro(), (12, 34, 56, 7));
267    /// ```
268    #[must_use]
269    pub fn hms_micro(self) -> (u8, u8, u8, u32) {
270        let (hour, minute, second, micro) = split_clock(self.0);
271        (
272            narrow_u8(hour),
273            narrow_u8(minute),
274            narrow_u8(second),
275            u32::try_from(micro).expect("a microsecond of a second fits u32"),
276        )
277    }
278}
279
280impl PgTimeTz {
281    /// The time `time` at `offset` seconds east of UTC, or `None` beyond PostgreSQL's 16 hours.
282    #[must_use]
283    pub const fn new(time: PgTime, offset: i32) -> Option<Self> {
284        if -TZDISP_LIMIT <= offset && offset <= TZDISP_LIMIT {
285            Some(Self {
286                time: time.0,
287                offset,
288            })
289        } else {
290            None
291        }
292    }
293
294    /// The time of day as written.
295    #[must_use]
296    pub const fn time(self) -> PgTime {
297        PgTime(self.time)
298    }
299
300    /// The offset east of UTC, in seconds.
301    #[must_use]
302    pub const fn offset(self) -> i32 {
303        self.offset
304    }
305
306    /// `timetz_cmp_internal`'s keys, the time at UTC and then PostgreSQL's zone, seconds west.
307    fn sort_key(self) -> (i64, i32) {
308        (
309            self.time - i64::from(self.offset) * USECS_PER_SEC,
310            -self.offset,
311        )
312    }
313}
314
315impl PartialOrd for PgTimeTz {
316    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
317        Some(self.cmp(other))
318    }
319}
320
321impl Ord for PgTimeTz {
322    fn cmp(&self, other: &Self) -> Ordering {
323        self.sort_key().cmp(&other.sort_key())
324    }
325}
326
327impl PgTimestamp {
328    /// `infinity`, PostgreSQL's `DT_NOEND`, after every timestamp.
329    pub const INFINITY: Self = Self(i64::MAX);
330    /// `-infinity`, PostgreSQL's `DT_NOBEGIN`, before every timestamp.
331    pub const NEG_INFINITY: Self = Self(i64::MIN);
332
333    /// The timestamp `micros` microseconds after 2000-01-01 00:00:00, as PostgreSQL stores it,
334    /// where `i64::MAX` and `i64::MIN` are the infinities, or `None` outside PostgreSQL's range.
335    #[must_use]
336    pub const fn from_pg_micros(micros: i64) -> Option<Self> {
337        if is_valid_timestamp(micros) || micros == i64::MAX || micros == i64::MIN {
338            Some(Self(micros))
339        } else {
340            None
341        }
342    }
343
344    /// The timestamp of `time` on a finite `date`, where 24:00:00 is midnight of the next day,
345    /// or `None` for an infinite date or outside PostgreSQL's range.
346    ///
347    /// ```
348    /// use sql_values::{PgDate, PgTime, PgTimestamp};
349    ///
350    /// let date = PgDate::from_ymd(2024, 12, 31).unwrap();
351    /// let at = PgTimestamp::new(date, PgTime::from_micros(86_400_000_000).unwrap()).unwrap();
352    /// assert_eq!(at.to_string(), "2025-01-01 00:00:00");
353    /// ```
354    #[must_use]
355    pub fn new(date: PgDate, time: PgTime) -> Option<Self> {
356        if !date.is_finite() {
357            return None;
358        }
359        i64::from(date.0)
360            .checked_mul(USECS_PER_DAY)
361            .and_then(|micros| micros.checked_add(time.0))
362            .and_then(Self::from_pg_micros)
363            .filter(|at| at.is_finite())
364    }
365
366    /// The timestamp PostgreSQL's arithmetic leaves in `micros`, unchecked as PostgreSQL leaves
367    /// it, as `AdjustTimestampForTypmod` rounds 294276-12-31 23:59:59.5 up to 294277-01-01.
368    pub(crate) const fn from_stored(micros: i64) -> Self {
369        Self(micros)
370    }
371
372    /// Microseconds from 2000-01-01 00:00:00, as PostgreSQL stores the timestamp.
373    #[must_use]
374    pub const fn pg_micros(self) -> i64 {
375        self.0
376    }
377
378    /// Whether the timestamp is neither `infinity` nor `-infinity`.
379    #[must_use]
380    pub const fn is_finite(self) -> bool {
381        self.0 != i64::MAX && self.0 != i64::MIN
382    }
383
384    /// The date, infinite for an infinite timestamp, as `timestamp_date` casts it.
385    #[must_use]
386    pub fn date(self) -> PgDate {
387        match self.0 {
388            i64::MAX => PgDate::INFINITY,
389            i64::MIN => PgDate::NEG_INFINITY,
390            micros => PgDate(narrow_days(micros.div_euclid(USECS_PER_DAY))),
391        }
392    }
393
394    /// The time of day, or `None` for an infinity.
395    #[must_use]
396    pub const fn time(self) -> Option<PgTime> {
397        if self.is_finite() {
398            Some(PgTime(self.0.rem_euclid(USECS_PER_DAY)))
399        } else {
400            None
401        }
402    }
403
404    /// PostgreSQL's `timestamp::timestamptz` with `zone` as the session's `TimeZone`, the local
405    /// clock resolved by `DetermineTimeZoneOffset`. A clock the spring-forward gap skips takes
406    /// the offset before the change, and a clock the fall-back repeats the offset after it.
407    ///
408    /// # Errors
409    ///
410    /// [`DateTimeError::TimestampOutOfRange`] where the instant leaves PostgreSQL's range, and
411    /// [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about a clock outside
412    /// jiff's years.
413    ///
414    /// ```
415    /// use sql_values::{InputContext, PgTimeZone, PgTimestamp};
416    ///
417    /// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
418    /// let gap = PgTimestamp::parse("2026-03-29 02:30:00", InputContext::new()).unwrap();
419    /// assert_eq!(gap.to_timestamptz(&rome).unwrap().to_string(), "2026-03-29 01:30:00+00");
420    /// ```
421    pub fn to_timestamptz(self, zone: &PgTimeZone) -> Result<PgTimestampTz, DateTimeError> {
422        if !self.is_finite() {
423            return Ok(PgTimestampTz(self.0));
424        }
425        let offset = local_offset(zone, self.0)?;
426        let instant = self.0 - i64::from(offset) * USECS_PER_SEC;
427        if is_valid_timestamp(instant) {
428            Ok(PgTimestampTz(instant))
429        } else {
430            Err(DateTimeError::TimestampOutOfRange)
431        }
432    }
433}
434
435impl PgTimestampTz {
436    /// `infinity`, PostgreSQL's `DT_NOEND`, after every instant.
437    pub const INFINITY: Self = Self(i64::MAX);
438    /// `-infinity`, PostgreSQL's `DT_NOBEGIN`, before every instant.
439    pub const NEG_INFINITY: Self = Self(i64::MIN);
440
441    /// The instant `micros` microseconds after 2000-01-01 00:00:00 UTC, as PostgreSQL stores it,
442    /// where `i64::MAX` and `i64::MIN` are the infinities, or `None` outside PostgreSQL's range.
443    #[must_use]
444    pub const fn from_pg_micros(micros: i64) -> Option<Self> {
445        match PgTimestamp::from_pg_micros(micros) {
446            Some(at) => Some(Self(at.0)),
447            None => None,
448        }
449    }
450
451    /// The instant PostgreSQL's arithmetic leaves in `micros`, unchecked as PostgreSQL leaves
452    /// it.
453    pub(crate) const fn from_stored(micros: i64) -> Self {
454        Self(micros)
455    }
456
457    /// Microseconds from 2000-01-01 00:00:00 UTC, as PostgreSQL stores the instant.
458    #[must_use]
459    pub const fn pg_micros(self) -> i64 {
460        self.0
461    }
462
463    /// Whether the instant is neither `infinity` nor `-infinity`.
464    #[must_use]
465    pub const fn is_finite(self) -> bool {
466        self.0 != i64::MAX && self.0 != i64::MIN
467    }
468
469    /// PostgreSQL's `timestamptz::timestamp` with `zone` as the session's `TimeZone`, the local
470    /// clock of the instant.
471    ///
472    /// # Errors
473    ///
474    /// [`DateTimeError::TimestampOutOfRange`] where the local clock leaves PostgreSQL's range,
475    /// and [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about an instant
476    /// outside jiff's years.
477    ///
478    /// ```
479    /// use sql_values::{InputContext, PgTimeZone, PgTimestampTz};
480    ///
481    /// let sydney = PgTimeZone::parse("Australia/Sydney").unwrap();
482    /// let at = PgTimestampTz::parse("2026-01-01 00:00:00+00", InputContext::new()).unwrap();
483    /// assert_eq!(at.to_timestamp(&sydney).unwrap().to_string(), "2026-01-01 11:00:00");
484    /// ```
485    pub fn to_timestamp(self, zone: &PgTimeZone) -> Result<PgTimestamp, DateTimeError> {
486        if !self.is_finite() {
487            return Ok(PgTimestamp(self.0));
488        }
489        let local = self.0 + i64::from(utc_offset(zone, self.0)?) * USECS_PER_SEC;
490        if is_valid_timestamp(local) {
491            Ok(PgTimestamp(local))
492        } else {
493            Err(DateTimeError::TimestampOutOfRange)
494        }
495    }
496
497    /// PostgreSQL's `timestamptz::date` with `zone` as the session's `TimeZone`, the local date
498    /// of the instant, which PostgreSQL does not range-check.
499    ///
500    /// # Errors
501    ///
502    /// [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about an instant outside
503    /// jiff's years.
504    pub fn to_date(self, zone: &PgTimeZone) -> Result<PgDate, DateTimeError> {
505        match self.0 {
506            i64::MAX => Ok(PgDate::INFINITY),
507            i64::MIN => Ok(PgDate::NEG_INFINITY),
508            utc => {
509                let local = utc + i64::from(utc_offset(zone, utc)?) * USECS_PER_SEC;
510                Ok(PgDate(narrow_days(local.div_euclid(USECS_PER_DAY))))
511            }
512        }
513    }
514}
515
516/// The offset `zone` has at the instant `utc`, microseconds from 2000-01-01 UTC, as
517/// `timestamp2tm` asks `pg_localtime` for it.
518pub(crate) fn utc_offset(zone: &PgTimeZone, utc: i64) -> Result<i32, DateTimeError> {
519    let unix = utc.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
520    zone.utc_offset(unix).ok_or(DateTimeError::OutsideJiffRange)
521}
522
523/// The offset `DetermineTimeZoneOffset` gives the local clock `local`, microseconds from
524/// 2000-01-01, in `zone`. A clock jiff cannot place that lies further past PostgreSQL's range
525/// than any of jiff's offsets reaches is [`DateTimeError::TimestampOutOfRange`], as PostgreSQL
526/// finds it after the offset.
527pub(crate) fn local_offset(zone: &PgTimeZone, local: i64) -> Result<i32, DateTimeError> {
528    /// jiff's offsets lie within 25:59:59 of UTC.
529    const JIFF_OFFSET_LIMIT: i64 = 26 * USECS_PER_HOUR;
530    let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
531    zone.local_offset(unix).ok_or(
532        if (MIN_TIMESTAMP - JIFF_OFFSET_LIMIT..END_TIMESTAMP + JIFF_OFFSET_LIMIT).contains(&local) {
533            DateTimeError::OutsideJiffRange
534        } else {
535            DateTimeError::TimestampOutOfRange
536        },
537    )
538}
539
540/// `DetermineTimeZoneAbbrevOffset`, the offset the uppercased `abbreviation` had in `zone` at the
541/// local clock `local`, microseconds from 2000-01-01, or the zone's own offset there when the
542/// zone never used it.
543pub(crate) fn abbreviation_offset(
544    zone: &PgTimeZone,
545    abbreviation: &str,
546    local: i64,
547) -> Result<i32, DateTimeError> {
548    let zone_offset = local_offset(zone, local)?;
549    let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS - i64::from(zone_offset);
550    Ok(zone
551        .interpret_abbreviation(abbreviation, unix)?
552        .map_or(zone_offset, |meaning| meaning.offset))
553}
554
555/// `IS_VALID_TIMESTAMP`.
556pub(crate) const fn is_valid_timestamp(micros: i64) -> bool {
557    MIN_TIMESTAMP <= micros && micros < END_TIMESTAMP
558}
559
560/// `IS_VALID_JULIAN`, which checks the lower bound only to the month.
561pub(crate) const fn is_valid_julian(year: i32, month: i32) -> bool {
562    (year > -4713 || (year == -4713 && month >= 11))
563        && (year < 5_874_898 || (year == 5_874_898 && month < 6))
564}
565
566/// `tm2timestamp`, the timestamp of a date within `IS_VALID_JULIAN` and a clock up to
567/// 24:00:00, with `offset` seconds east subtracted, or `None` outside PostgreSQL's range.
568pub(crate) fn tm2timestamp(
569    year: i32,
570    month: i32,
571    day: i32,
572    clock: i64,
573    offset: i32,
574) -> Option<i64> {
575    if !is_valid_julian(year, month) {
576        return None;
577    }
578    let days = i64::from(date2j(year, month, day) - POSTGRES_EPOCH_JDATE);
579    days.checked_mul(USECS_PER_DAY)?
580        .checked_add(clock)?
581        .checked_sub(i64::from(offset) * USECS_PER_SEC)
582        .filter(|&micros| is_valid_timestamp(micros))
583}
584
585/// `timestamp2tm` without a zone, the year, month, day and clock of a timestamp whose Julian
586/// day is at least -1.
587pub(crate) fn timestamp2tm(micros: i64) -> (i32, i32, i32, i64) {
588    let (year, month, day) =
589        j2date(narrow_days(micros.div_euclid(USECS_PER_DAY)) + POSTGRES_EPOCH_JDATE);
590    (year, month, day, micros.rem_euclid(USECS_PER_DAY))
591}
592
593/// `date2j`, the Julian day of a proleptic Gregorian date within `IS_VALID_JULIAN`.
594pub(crate) const fn date2j(year: i32, month: i32, day: i32) -> i32 {
595    let (year, month) = if month > 2 {
596        (year + 4800, month + 1)
597    } else {
598        (year + 4799, month + 13)
599    };
600    let century = year / 100;
601    let mut julian = year * 365 - 32_167;
602    julian += year / 4 - century + century / 4;
603    julian + 7_834 * month / 256 + day
604}
605
606/// `j2date`, the proleptic Gregorian date of a Julian day from -1.
607pub(crate) const fn j2date(julian_day: i32) -> (i32, i32, i32) {
608    // Unsigned as in C, where the conversion wraps and every intermediate stays below 2^32.
609    let mut julian = julian_day.cast_unsigned().wrapping_add(32_044);
610    let mut quad = julian / 146_097;
611    let extra = (julian - quad * 146_097) * 4 + 3;
612    julian += 60 + quad * 3 + extra / 146_097;
613    quad = julian / 1_461;
614    julian -= quad * 1_461;
615    let mut year = julian * 4 / 1_461;
616    julian = if year == 0 {
617        (julian + 306) % 366
618    } else {
619        (julian + 305) % 365
620    } + 123;
621    year += quad * 4;
622    let quad = julian * 2_141 / 65_536;
623    let day = julian - 7_834 * quad / 256;
624    let month = (quad + 10) % 12 + 1;
625    // The year is below 2^31 + 4800 and the day and month below 32.
626    (
627        year.cast_signed() - 4_800,
628        month.cast_signed(),
629        day.cast_signed(),
630    )
631}
632
633/// Days in `month` of the proleptic Gregorian `year`, `0` being 1 BC.
634pub(crate) const fn days_in_month(year: i32, month: i32) -> i32 {
635    let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
636    match month {
637        2 if leap => 29,
638        2 => 28,
639        4 | 6 | 9 | 11 => 30,
640        _ => 31,
641    }
642}
643
644/// Days from 2000-01-01 of a value PostgreSQL holds, which always fit `int`.
645fn narrow_days(days: i64) -> i32 {
646    i32::try_from(days).expect("a timestamp lies under 2^31 days from 2000-01-01")
647}
648
649/// A month, day or clock field, which always fits `u8`.
650fn narrow_u8(field: i64) -> u8 {
651    u8::try_from(field).expect("a calendar or clock field fits u8")
652}
653
654/// The hour, minute, second and microsecond of a clock up to 24:00:00.
655const fn split_clock(micros: i64) -> (i64, i64, i64, i64) {
656    (
657        micros / USECS_PER_HOUR,
658        micros % USECS_PER_HOUR / USECS_PER_MINUTE,
659        micros % USECS_PER_MINUTE / USECS_PER_SEC,
660        micros % USECS_PER_SEC,
661    )
662}
663
664/// `EncodeDateOnly` under `DateStyle` `ISO`, `Y BC` for year `1 - Y`, with the era left to the
665/// caller.
666fn write_ymd(f: &mut fmt::Formatter<'_>, year: i32, month: i32, day: i32) -> fmt::Result {
667    let shown = if year > 0 { year } else { 1 - year };
668    write!(f, "{shown:04}-{month:02}-{day:02}")
669}
670
671/// `HH:MM:SS` and `AppendSeconds`' fraction without trailing zeros.
672fn write_clock(f: &mut fmt::Formatter<'_>, micros: i64) -> fmt::Result {
673    let (hour, minute, second, mut fraction) = split_clock(micros);
674    write!(f, "{hour:02}:{minute:02}:{second:02}")?;
675    if fraction > 0 {
676        let mut width = 6;
677        while fraction % 10 == 0 {
678            fraction /= 10;
679            width -= 1;
680        }
681        write!(f, ".{fraction:0width$}")?;
682    }
683    Ok(())
684}
685
686/// `EncodeTimezone`, `±HH`, `±HH:MM` or `±HH:MM:SS` of an offset east of UTC.
687fn write_offset(f: &mut fmt::Formatter<'_>, offset: i32) -> fmt::Result {
688    let sign = if offset >= 0 { '+' } else { '-' };
689    let magnitude = offset.unsigned_abs();
690    let (hour, minute, second) = (magnitude / 3_600, magnitude / 60 % 60, magnitude % 60);
691    write!(f, "{sign}{hour:02}")?;
692    if second != 0 {
693        write!(f, ":{minute:02}:{second:02}")
694    } else if minute != 0 {
695        write!(f, ":{minute:02}")
696    } else {
697        Ok(())
698    }
699}
700
701/// `EncodeDateTime` under `DateStyle` `ISO`, with `+00` for a `timestamptz` in `UTC`.
702fn write_timestamp(f: &mut fmt::Formatter<'_>, micros: i64, zone: bool) -> fmt::Result {
703    match micros {
704        i64::MAX => return f.write_str("infinity"),
705        i64::MIN => return f.write_str("-infinity"),
706        _ => {}
707    }
708    let (year, month, day, clock) = timestamp2tm(micros);
709    write_ymd(f, year, month, day)?;
710    f.write_str(" ")?;
711    write_clock(f, clock)?;
712    if zone {
713        f.write_str("+00")?;
714    }
715    if year <= 0 {
716        f.write_str(" BC")?;
717    }
718    Ok(())
719}
720
721impl fmt::Display for PgDate {
722    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723        match self.0 {
724            i32::MAX => f.write_str("infinity"),
725            i32::MIN => f.write_str("-infinity"),
726            days => {
727                let (year, month, day) = j2date(days + POSTGRES_EPOCH_JDATE);
728                write_ymd(f, year, month, day)?;
729                if year <= 0 {
730                    f.write_str(" BC")?;
731                }
732                Ok(())
733            }
734        }
735    }
736}
737
738impl fmt::Display for PgTime {
739    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
740        write_clock(f, self.0)
741    }
742}
743
744impl fmt::Display for PgTimeTz {
745    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
746        write_clock(f, self.time)?;
747        write_offset(f, self.offset)
748    }
749}
750
751impl fmt::Display for PgTimestamp {
752    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753        write_timestamp(f, self.0, false)
754    }
755}
756
757impl fmt::Display for PgTimestampTz {
758    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
759        write_timestamp(f, self.0, true)
760    }
761}
762
763impl TryFrom<i32> for PgDate {
764    type Error = DateTimeError;
765
766    fn try_from(days: i32) -> Result<Self, Self::Error> {
767        Self::from_pg_days(days).ok_or(DateTimeError::DateOutOfRange)
768    }
769}
770
771impl From<PgDate> for i32 {
772    fn from(date: PgDate) -> Self {
773        date.0
774    }
775}
776
777impl TryFrom<i64> for PgTime {
778    type Error = DateTimeError;
779
780    fn try_from(micros: i64) -> Result<Self, Self::Error> {
781        Self::from_micros(micros).ok_or(DateTimeError::FieldValueOutOfRange)
782    }
783}
784
785impl From<PgTime> for i64 {
786    fn from(time: PgTime) -> Self {
787        time.0
788    }
789}
790
791impl TryFrom<(i64, i32)> for PgTimeTz {
792    type Error = DateTimeError;
793
794    fn try_from((micros, offset): (i64, i32)) -> Result<Self, Self::Error> {
795        let time = PgTime::try_from(micros)?;
796        Self::new(time, offset).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange)
797    }
798}
799
800impl From<PgTimeTz> for (i64, i32) {
801    fn from(time: PgTimeTz) -> Self {
802        (time.time, time.offset)
803    }
804}
805
806impl TryFrom<i64> for PgTimestamp {
807    type Error = DateTimeError;
808
809    fn try_from(micros: i64) -> Result<Self, Self::Error> {
810        Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
811    }
812}
813
814impl From<PgTimestamp> for i64 {
815    fn from(at: PgTimestamp) -> Self {
816        at.0
817    }
818}
819
820impl TryFrom<i64> for PgTimestampTz {
821    type Error = DateTimeError;
822
823    fn try_from(micros: i64) -> Result<Self, Self::Error> {
824        Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
825    }
826}
827
828impl From<PgTimestampTz> for i64 {
829    fn from(at: PgTimestampTz) -> Self {
830        at.0
831    }
832}