Skip to main content

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