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