1use alloc::string::String;
5use core::fmt::Write;
6
7use super::{
8 MONTHS_PER_YEAR, PgDate, PgTime, PgTimeZone, PgTimestamp, PgTimestampTz, USECS_PER_SEC, date2j,
9 local_time_type, split_clock, timestamp2tm,
10};
11use crate::postgres::PgInterval;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
16pub enum TemporalFormatError {
17 #[error("invalid format specification for an interval value")]
20 InvalidForInterval,
21 #[error("time zone format value too long")]
23 TimeZoneFormatValueTooLong,
24 #[error("date out of range for timestamp")]
27 DateOutOfRangeForTimestamp,
28}
29
30const MONTHS: [&str; 12] = [
31 "January",
32 "February",
33 "March",
34 "April",
35 "May",
36 "June",
37 "July",
38 "August",
39 "September",
40 "October",
41 "November",
42 "December",
43];
44
45const DAYS: [&str; 7] = [
46 "Sunday",
47 "Monday",
48 "Tuesday",
49 "Wednesday",
50 "Thursday",
51 "Friday",
52 "Saturday",
53];
54
55const ROMAN_MONTHS: [&str; 12] = [
57 "XII", "XI", "X", "IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I",
58];
59
60struct Fields<'a> {
62 year: i32,
63 month: i32,
64 day: i32,
65 hour: i64,
66 minute: i64,
67 second: i64,
68 microsecond: i64,
69 weekday: i32,
70 year_day: i32,
71 offset: i32,
73 zone: Option<&'a str>,
74 interval: bool,
77}
78
79impl Fields<'_> {
80 fn civil(micros: i64) -> Self {
83 let (year, month, day, clock) = timestamp2tm(micros);
84 let (hour, minute, second, microsecond) = split_clock(clock);
85 let julian = date2j(year, month, day);
86 Self {
87 year,
88 month,
89 day,
90 hour,
91 minute,
92 second,
93 microsecond,
94 weekday: (julian + 1) % 7,
95 year_day: julian - date2j(year, 1, 1) + 1,
96 offset: 0,
97 zone: None,
98 interval: false,
99 }
100 }
101
102 fn interval(interval: PgInterval) -> Self {
105 let (hour, minute, second, microsecond) = split_clock(interval.microseconds);
106 Self {
107 year: interval.months / MONTHS_PER_YEAR,
108 month: interval.months % MONTHS_PER_YEAR,
109 day: interval.days,
110 hour,
111 minute,
112 second,
113 microsecond,
114 weekday: 0,
115 year_day: interval.months.wrapping_mul(30).wrapping_add(interval.days),
116 offset: 0,
117 zone: None,
118 interval: true,
119 }
120 }
121
122 const fn era_year(&self, year: i32) -> i32 {
124 if self.interval || year > 0 {
125 year
126 } else {
127 1 - year
128 }
129 }
130}
131
132#[derive(Debug, Clone, Copy)]
134enum Case {
135 Upper,
136 Capitalized,
137 Lower,
138}
139
140#[derive(Debug, Clone, Copy)]
142enum Keyword {
143 Meridiem([&'static str; 2]),
145 Era([&'static str; 2]),
147 Hour12,
148 Hour24,
149 Minute,
150 Second,
151 Fraction(u8),
153 SecondsOfDay,
154 ZoneAbbreviation {
155 lower: bool,
156 },
157 ZoneHours,
158 ZoneMinutes,
159 UtcOffset,
160 MonthName(Case),
161 MonthAbbreviation(Case),
162 Month,
163 DayName(Case),
164 DayAbbreviation(Case),
165 DayOfYear,
166 IsoDayOfYear,
167 DayOfMonth,
168 DayOfWeek,
169 IsoDayOfWeek,
170 WeekOfYear,
171 IsoWeek,
172 Quarter,
173 Century,
174 YearWithComma,
175 Year {
176 digits: usize,
177 },
178 IsoYear {
179 digits: usize,
180 },
181 RomanMonth {
182 upper: bool,
183 },
184 WeekOfMonth,
185 Julian,
186 FixedFormat,
187}
188
189const KEYWORDS: &[(&str, Keyword)] = {
191 use Case::{Capitalized, Lower, Upper};
192 use Keyword::*;
193 &[
194 ("A.D.", Era(["A.D.", "B.C."])),
195 ("A.M.", Meridiem(["A.M.", "P.M."])),
196 ("AD", Era(["AD", "BC"])),
197 ("AM", Meridiem(["AM", "PM"])),
198 ("B.C.", Era(["A.D.", "B.C."])),
199 ("BC", Era(["AD", "BC"])),
200 ("CC", Century),
201 ("DAY", DayName(Upper)),
202 ("DDD", DayOfYear),
203 ("DD", DayOfMonth),
204 ("DY", DayAbbreviation(Upper)),
205 ("Day", DayName(Capitalized)),
206 ("Dy", DayAbbreviation(Capitalized)),
207 ("D", DayOfWeek),
208 ("FF1", Fraction(1)),
209 ("FF2", Fraction(2)),
210 ("FF3", Fraction(3)),
211 ("FF4", Fraction(4)),
212 ("FF5", Fraction(5)),
213 ("FF6", Fraction(6)),
214 ("FX", FixedFormat),
215 ("HH24", Hour24),
216 ("HH12", Hour12),
217 ("HH", Hour12),
218 ("IDDD", IsoDayOfYear),
219 ("ID", IsoDayOfWeek),
220 ("IW", IsoWeek),
221 ("IYYY", IsoYear { digits: 4 }),
222 ("IYY", IsoYear { digits: 3 }),
223 ("IY", IsoYear { digits: 2 }),
224 ("I", IsoYear { digits: 1 }),
225 ("J", Julian),
226 ("MI", Minute),
227 ("MM", Month),
228 ("MONTH", MonthName(Upper)),
229 ("MON", MonthAbbreviation(Upper)),
230 ("MS", Fraction(3)),
231 ("Month", MonthName(Capitalized)),
232 ("Mon", MonthAbbreviation(Capitalized)),
233 ("OF", UtcOffset),
234 ("P.M.", Meridiem(["A.M.", "P.M."])),
235 ("PM", Meridiem(["AM", "PM"])),
236 ("Q", Quarter),
237 ("RM", RomanMonth { upper: true }),
238 ("SSSSS", SecondsOfDay),
239 ("SSSS", SecondsOfDay),
240 ("SS", Second),
241 ("TZH", ZoneHours),
242 ("TZM", ZoneMinutes),
243 ("TZ", ZoneAbbreviation { lower: false }),
244 ("US", Fraction(6)),
245 ("WW", WeekOfYear),
246 ("W", WeekOfMonth),
247 ("Y,YYY", YearWithComma),
248 ("YYYY", Year { digits: 4 }),
249 ("YYY", Year { digits: 3 }),
250 ("YY", Year { digits: 2 }),
251 ("Y", Year { digits: 1 }),
252 ("a.d.", Era(["a.d.", "b.c."])),
253 ("a.m.", Meridiem(["a.m.", "p.m."])),
254 ("ad", Era(["ad", "bc"])),
255 ("am", Meridiem(["am", "pm"])),
256 ("b.c.", Era(["a.d.", "b.c."])),
257 ("bc", Era(["ad", "bc"])),
258 ("cc", Century),
259 ("day", DayName(Lower)),
260 ("ddd", DayOfYear),
261 ("dd", DayOfMonth),
262 ("dy", DayAbbreviation(Lower)),
263 ("d", DayOfWeek),
264 ("ff1", Fraction(1)),
265 ("ff2", Fraction(2)),
266 ("ff3", Fraction(3)),
267 ("ff4", Fraction(4)),
268 ("ff5", Fraction(5)),
269 ("ff6", Fraction(6)),
270 ("fx", FixedFormat),
271 ("hh24", Hour24),
272 ("hh12", Hour12),
273 ("hh", Hour12),
274 ("iddd", IsoDayOfYear),
275 ("id", IsoDayOfWeek),
276 ("iw", IsoWeek),
277 ("iyyy", IsoYear { digits: 4 }),
278 ("iyy", IsoYear { digits: 3 }),
279 ("iy", IsoYear { digits: 2 }),
280 ("i", IsoYear { digits: 1 }),
281 ("j", Julian),
282 ("mi", Minute),
283 ("mm", Month),
284 ("month", MonthName(Lower)),
285 ("mon", MonthAbbreviation(Lower)),
286 ("ms", Fraction(3)),
287 ("of", UtcOffset),
288 ("p.m.", Meridiem(["a.m.", "p.m."])),
289 ("pm", Meridiem(["am", "pm"])),
290 ("q", Quarter),
291 ("rm", RomanMonth { upper: false }),
292 ("sssss", SecondsOfDay),
293 ("ssss", SecondsOfDay),
294 ("ss", Second),
295 ("tzh", ZoneHours),
296 ("tzm", ZoneMinutes),
297 ("tz", ZoneAbbreviation { lower: true }),
298 ("us", Fraction(6)),
299 ("ww", WeekOfYear),
300 ("w", WeekOfMonth),
301 ("y,yyy", YearWithComma),
302 ("yyyy", Year { digits: 4 }),
303 ("yyy", Year { digits: 3 }),
304 ("yy", Year { digits: 2 }),
305 ("y", Year { digits: 1 }),
306 ]
307};
308
309#[derive(Debug, Clone, Copy)]
311enum Ordinal {
312 Upper,
313 Lower,
314}
315
316#[derive(Debug, Clone, Copy)]
318struct Field {
319 keyword: Keyword,
320 fill: bool,
322 translate: bool,
324 ordinal: Option<Ordinal>,
325}
326
327#[derive(Debug, Clone, Copy)]
329enum Node<'a> {
330 Text(&'a str),
331 Field(Field),
332}
333
334struct Nodes<'a> {
336 rest: &'a str,
337 quoted: bool,
338}
339
340impl<'a> Nodes<'a> {
341 const fn new(template: &'a str) -> Self {
342 Self {
343 rest: template,
344 quoted: false,
345 }
346 }
347
348 fn eat(&mut self, prefix: &str) -> bool {
350 match self.rest.strip_prefix(prefix) {
351 Some(rest) => {
352 self.rest = rest;
353 true
354 }
355 None => false,
356 }
357 }
358
359 fn character(&mut self, escaped: bool) -> &'a str {
361 if escaped {
362 self.rest = &self.rest[1..];
363 }
364 let width = self.rest.chars().next().map_or(0, char::len_utf8);
365 let (character, rest) = self.rest.split_at(width);
366 self.rest = rest;
367 character
368 }
369}
370
371impl<'a> Iterator for Nodes<'a> {
372 type Item = Node<'a>;
373
374 fn next(&mut self) -> Option<Node<'a>> {
375 loop {
376 if self.rest.is_empty() {
377 return None;
378 }
379 if self.quoted {
380 if self.eat("\"") {
381 self.quoted = false;
382 continue;
383 }
384 let escaped = self.rest.starts_with('\\') && self.rest.len() > 1;
386 return Some(Node::Text(self.character(escaped)));
387 }
388 let fill = self.eat("FM") || self.eat("fm");
390 let translate = !fill && (self.eat("TM") || self.eat("tm"));
391 if let Some(&(name, keyword)) = KEYWORDS
392 .iter()
393 .find(|(name, _)| self.rest.starts_with(name))
394 {
395 self.rest = &self.rest[name.len()..];
396 let ordinal = if self.eat("TH") {
397 Some(Ordinal::Upper)
398 } else if self.eat("th") {
399 Some(Ordinal::Lower)
400 } else {
401 self.eat("SP");
403 None
404 };
405 return Some(Node::Field(Field {
406 keyword,
407 fill,
408 translate,
409 ordinal,
410 }));
411 }
412 if self.rest.is_empty() {
413 return None;
414 }
415 if self.eat("\"") {
416 self.quoted = true;
417 continue;
418 }
419 let escaped = self.rest.starts_with("\\\"");
421 return Some(Node::Text(self.character(escaped)));
422 }
423 }
424}
425
426fn format(template: &str, fields: &Fields<'_>) -> Result<String, TemporalFormatError> {
428 let mut out = String::with_capacity(template.len());
429 for node in Nodes::new(template) {
430 match node {
431 Node::Text(text) => out.push_str(text),
432 Node::Field(field) => field.write(fields, &mut out)?,
433 }
434 }
435 Ok(out)
436}
437
438const fn j2day(julian: i32) -> i32 {
440 julian.wrapping_add(1).rem_euclid(7)
441}
442
443const fn iso_week_start(year: i32) -> i32 {
445 let day4 = date2j(year, 1, 4);
446 day4.wrapping_sub(j2day(day4.wrapping_sub(1)))
447}
448
449const fn date2isoweek(year: i32, month: i32, day: i32) -> i32 {
451 let julian = date2j(year, month, day);
452 let mut start = iso_week_start(year);
453 if julian < start {
454 start = iso_week_start(year.wrapping_sub(1));
455 }
456 let mut week = julian.wrapping_sub(start) / 7 + 1;
457 if week >= 52 {
458 let next = iso_week_start(year.wrapping_add(1));
459 if julian >= next {
460 week = julian.wrapping_sub(next) / 7 + 1;
461 }
462 }
463 week
464}
465
466const fn date2isoyear(year: i32, month: i32, day: i32) -> i32 {
468 let julian = date2j(year, month, day);
469 let mut year = year;
470 let mut start = iso_week_start(year);
471 if julian < start {
472 year = year.wrapping_sub(1);
473 start = iso_week_start(year);
474 }
475 if julian.wrapping_sub(start) / 7 + 1 >= 52 && julian >= iso_week_start(year.wrapping_add(1)) {
476 year = year.wrapping_add(1);
477 }
478 year
479}
480
481const fn signed_width(fill: bool, negative: bool, width: usize) -> usize {
483 if fill {
484 0
485 } else if negative {
486 width + 1
487 } else {
488 width
489 }
490}
491
492impl Field {
493 fn write(self, fields: &Fields<'_>, out: &mut String) -> Result<(), TemporalFormatError> {
495 let start = out.len();
496 let fill = self.fill;
497 let width = |width| if fill { 0 } else { width };
498 if fields.interval && self.keyword.needs_calendar_date() {
499 return Err(TemporalFormatError::InvalidForInterval);
500 }
501 match self.keyword {
502 Keyword::Meridiem([morning, afternoon]) => {
503 out.push_str(if fields.hour % 24 >= 12 {
504 afternoon
505 } else {
506 morning
507 });
508 }
509 Keyword::Era([common, before]) => {
510 out.push_str(if fields.year <= 0 { before } else { common });
511 }
512 Keyword::Hour12 => {
513 let hour = match fields.hour % 12 {
514 0 => 12,
515 hour => hour,
516 };
517 number(out, hour, signed_width(fill, fields.hour < 0, 2));
518 }
519 Keyword::Hour24 => number(out, fields.hour, signed_width(fill, fields.hour < 0, 2)),
520 Keyword::Minute => {
521 number(out, fields.minute, signed_width(fill, fields.minute < 0, 2));
522 }
523 Keyword::Second => {
524 number(out, fields.second, signed_width(fill, fields.second < 0, 2));
525 }
526 Keyword::Fraction(digits) => {
527 let divisor = 10_i64.pow(u32::from(6 - digits));
528 number(out, fields.microsecond / divisor, usize::from(digits));
529 }
530 Keyword::SecondsOfDay => {
531 number(
532 out,
533 fields.hour * 3_600 + fields.minute * 60 + fields.second,
534 0,
535 );
536 }
537 Keyword::ZoneAbbreviation { lower } => {
538 if let Some(zone) = fields.zone {
539 if zone.len() > 24 {
540 return Err(TemporalFormatError::TimeZoneFormatValueTooLong);
541 }
542 if lower {
543 out.extend(zone.chars().map(|c| c.to_ascii_lowercase()));
544 } else {
545 out.push_str(zone);
546 }
547 }
548 }
549 Keyword::ZoneHours => {
550 out.push(offset_sign(fields.offset));
551 number(out, (fields.offset.unsigned_abs() / 3_600).into(), 2);
552 }
553 Keyword::ZoneMinutes => {
554 number(out, (fields.offset.unsigned_abs() % 3_600 / 60).into(), 2);
555 }
556 Keyword::UtcOffset => {
557 let magnitude = fields.offset.unsigned_abs();
558 out.push(offset_sign(fields.offset));
559 number(out, (magnitude / 3_600).into(), width(2));
560 if !magnitude.is_multiple_of(3_600) {
561 out.push(':');
562 number(out, (magnitude % 3_600 / 60).into(), 2);
563 }
564 }
565 Keyword::MonthName(case) => {
566 self.name(out, MONTHS[month_index(fields.month)], case, 9);
567 }
568 Keyword::MonthAbbreviation(case) => {
569 self.name(out, &MONTHS[month_index(fields.month)][..3], case, 0);
570 }
571 Keyword::Month => {
572 let month = fields.month.into();
573 number(out, month, signed_width(fill, month < 0, 2));
574 }
575 Keyword::DayName(case) => self.name(out, DAYS[day_index(fields.weekday)], case, 9),
576 Keyword::DayAbbreviation(case) => {
577 self.name(out, &DAYS[day_index(fields.weekday)][..3], case, 0);
578 }
579 Keyword::DayOfYear => number(out, fields.year_day.into(), width(3)),
580 Keyword::IsoDayOfYear => {
581 let year = date2isoyear(fields.year, fields.month, fields.day);
582 let julian = date2j(fields.year, fields.month, fields.day);
583 let day = julian.wrapping_sub(iso_week_start(year)).wrapping_add(1);
584 number(out, day.into(), width(3));
585 }
586 Keyword::DayOfMonth => number(out, fields.day.into(), width(2)),
587 Keyword::DayOfWeek => number(out, (fields.weekday + 1).into(), 0),
588 Keyword::IsoDayOfWeek => {
589 let day = if fields.weekday == 0 {
590 7
591 } else {
592 fields.weekday
593 };
594 number(out, day.into(), 0);
595 }
596 Keyword::WeekOfYear => {
597 let week = fields.year_day.wrapping_sub(1) / 7 + 1;
598 number(out, week.into(), width(2));
599 }
600 Keyword::IsoWeek => {
601 let week = date2isoweek(fields.year, fields.month, fields.day);
602 number(out, week.into(), width(2));
603 }
604 Keyword::Quarter => {
605 if fields.month == 0 {
606 return Ok(());
607 }
608 number(out, ((fields.month - 1) / 3 + 1).into(), 0);
609 }
610 Keyword::Century => {
611 let century = if fields.interval {
612 fields.year / 100
613 } else if fields.year > 0 {
614 (fields.year - 1) / 100 + 1
615 } else {
616 fields.year / 100 - 1
617 };
618 let width = if (-99..=99).contains(¢ury) {
619 signed_width(fill, century < 0, 2)
620 } else {
621 0
622 };
623 number(out, century.into(), width);
624 }
625 Keyword::YearWithComma => {
626 let year = fields.era_year(fields.year);
627 let thousands = year / 1_000;
628 number(out, thousands.into(), 0);
629 out.push(',');
630 number(out, (year - thousands * 1_000).into(), 3);
631 }
632 Keyword::Year { digits } => {
633 self.year(out, fields, fields.era_year(fields.year), digits);
634 }
635 Keyword::IsoYear { digits } => {
636 let year = date2isoyear(fields.year, fields.month, fields.day);
637 self.year(out, fields, fields.era_year(year), digits);
638 }
639 Keyword::RomanMonth { upper } => {
640 if fields.month == 0 && fields.year == 0 {
641 return Ok(());
642 }
643 let index = match fields.month {
644 0 if fields.year >= 0 => 0,
645 0 => 11,
646 month if month < 0 => -(month + 1),
647 month => 12 - month,
648 };
649 let numeral = ROMAN_MONTHS[usize::try_from(index).expect("a month within a year")];
650 let padding = if fill { 0 } else { 4 };
651 let numeral_start = out.len();
652 if upper {
653 out.push_str(numeral);
654 } else {
655 out.extend(numeral.chars().map(|c| c.to_ascii_lowercase()));
656 }
657 pad(out, numeral_start, padding);
658 return Ok(());
659 }
660 Keyword::WeekOfMonth => {
661 number(out, (fields.day.wrapping_sub(1) / 7 + 1).into(), 0);
662 }
663 Keyword::Julian => {
664 number(out, date2j(fields.year, fields.month, fields.day).into(), 0);
665 }
666 Keyword::FixedFormat => return Ok(()),
667 }
668 if let Some(ordinal) = self.ordinal
669 && self.keyword.is_number()
670 {
671 append_ordinal(out, start, ordinal);
672 }
673 Ok(())
674 }
675
676 fn name(self, out: &mut String, name: &str, case: Case, padding: usize) {
678 let start = out.len();
679 match case {
680 Case::Upper => out.extend(name.chars().map(|c| c.to_ascii_uppercase())),
681 Case::Capitalized => out.push_str(name),
682 Case::Lower => out.extend(name.chars().map(|c| c.to_ascii_lowercase())),
683 }
684 if !self.fill && !self.translate {
685 pad(out, start, padding);
686 }
687 }
688
689 fn year(self, out: &mut String, fields: &Fields<'_>, year: i32, digits: usize) {
691 let (value, width) = match digits {
692 4 => (year, 4),
693 3 => (year % 1_000, 3),
694 2 => (year % 100, 2),
695 _ => {
696 number(out, (year % 10).into(), 1);
697 return;
698 }
699 };
700 let negative = fields.era_year(fields.year) < 0;
701 number(out, value.into(), signed_width(self.fill, negative, width));
702 }
703}
704
705impl Keyword {
706 const fn needs_calendar_date(self) -> bool {
708 matches!(
709 self,
710 Self::Era(_)
711 | Self::ZoneAbbreviation { .. }
712 | Self::ZoneHours
713 | Self::ZoneMinutes
714 | Self::UtcOffset
715 | Self::MonthName(_)
716 | Self::MonthAbbreviation(_)
717 | Self::DayName(_)
718 | Self::DayAbbreviation(_)
719 | Self::DayOfWeek
720 | Self::IsoDayOfWeek
721 )
722 }
723
724 const fn is_number(self) -> bool {
726 !matches!(
727 self,
728 Self::Meridiem { .. }
729 | Self::Era { .. }
730 | Self::ZoneAbbreviation { .. }
731 | Self::ZoneHours
732 | Self::ZoneMinutes
733 | Self::UtcOffset
734 | Self::MonthName(_)
735 | Self::MonthAbbreviation(_)
736 | Self::DayName(_)
737 | Self::DayAbbreviation(_)
738 | Self::RomanMonth { .. }
739 | Self::FixedFormat
740 )
741 }
742}
743
744fn month_index(month: i32) -> usize {
746 usize::try_from(month - 1).expect("a calendar month from 1 to 12")
747}
748
749fn day_index(weekday: i32) -> usize {
753 usize::try_from(weekday.rem_euclid(7)).expect("a remainder of 7 fits usize")
754}
755
756const fn offset_sign(offset: i32) -> char {
757 if offset >= 0 { '+' } else { '-' }
758}
759
760fn number(out: &mut String, value: i64, width: usize) {
762 write!(out, "{value:0width$}").expect("a String takes any text");
763}
764
765fn pad(out: &mut String, start: usize, width: usize) {
767 let written = out[start..].chars().count();
768 out.extend(core::iter::repeat_n(' ', width.saturating_sub(written)));
769}
770
771fn append_ordinal(out: &mut String, start: usize, ordinal: Ordinal) {
774 let digits = &out.as_bytes()[start..];
775 let last = digits.last().copied();
776 let teen = digits.len() > 1 && digits[digits.len() - 2] == b'1';
777 let ending = match (last, teen) {
778 (Some(b'1'), false) => "st",
779 (Some(b'2'), false) => "nd",
780 (Some(b'3'), false) => "rd",
781 _ => "th",
782 };
783 match ordinal {
784 Ordinal::Upper => out.extend(ending.chars().map(|c| c.to_ascii_uppercase())),
785 Ordinal::Lower => out.push_str(ending),
786 }
787}
788
789impl PgTimestamp {
790 #[must_use]
812 pub fn to_char(self, template: &str) -> Option<String> {
813 if template.is_empty() || !self.is_finite() {
814 return None;
815 }
816 let fields = Fields::civil(self.pg_micros());
817 let text = format(template, &fields);
818 Some(text.expect("only an interval's fields or a zone abbreviation refuse a template"))
819 }
820}
821
822impl PgTimestampTz {
823 pub fn to_char(
853 self,
854 template: &str,
855 zone: &PgTimeZone,
856 ) -> Result<Option<String>, TemporalFormatError> {
857 if template.is_empty() || !self.is_finite() {
858 return Ok(None);
859 }
860 let utc = self.pg_micros();
861 let (offset, abbreviation) = local_time_type(zone, utc);
862 let fields = Fields {
863 offset,
864 zone: Some(abbreviation.as_str()),
865 ..Fields::civil(utc + i64::from(offset) * USECS_PER_SEC)
866 };
867 format(template, &fields).map(Some)
868 }
869}
870
871impl PgDate {
872 pub fn to_char(
902 self,
903 template: &str,
904 zone: &PgTimeZone,
905 ) -> Result<Option<String>, TemporalFormatError> {
906 let out_of_range = TemporalFormatError::DateOutOfRangeForTimestamp;
908 let midnight = self.to_timestamp().map_err(|_| out_of_range)?;
909 let instant = midnight.to_timestamptz(zone).map_err(|_| out_of_range)?;
910 instant.to_char(template, zone)
911 }
912}
913
914impl PgInterval {
915 pub fn to_char(self, template: &str) -> Result<Option<String>, TemporalFormatError> {
943 if template.is_empty() || !self.is_finite() {
944 return Ok(None);
945 }
946 format(template, &Fields::interval(self)).map(Some)
947 }
948}
949
950impl PgTime {
951 pub fn to_char(self, template: &str) -> Result<Option<String>, TemporalFormatError> {
971 let interval = PgInterval {
972 months: 0,
973 days: 0,
974 microseconds: self.micros(),
975 };
976 interval.to_char(template)
977 }
978}