1use chrono::{Datelike, NaiveDate, NaiveTime, Timelike};
4
5use crate::{Error, Result};
6
7use super::pattern::FieldKind;
8use super::zone::{add_offset, zone_display};
9use super::{time_to_nanos, Temporal};
10
11mod duration;
12mod iso;
13
14use iso::format_offset;
15pub(in crate::temporal) use iso::{format_zone_offset, render};
16
17use duration::format_duration_pattern;
18
19pub(super) const MONTH_NAMES: [&str; 12] = [
23 "January",
24 "February",
25 "March",
26 "April",
27 "May",
28 "June",
29 "July",
30 "August",
31 "September",
32 "October",
33 "November",
34 "December",
35];
36
37pub(super) const WEEKDAY_NAMES: [&str; 7] = [
39 "Monday",
40 "Tuesday",
41 "Wednesday",
42 "Thursday",
43 "Friday",
44 "Saturday",
45 "Sunday",
46];
47
48pub(super) fn fraction_width(width: usize) -> Result<usize> {
52 if (1..=9).contains(&width) {
53 Ok(width)
54 } else {
55 Err(invalid_pattern_character())
56 }
57}
58
59fn invalid_pattern_character() -> Error {
63 Error::syntax("InvalidPatternCharacter")
64}
65
66fn invalid_pattern_symbol(c: char) -> Error {
70 Error::syntax(format!(
71 "InvalidPatternCharacter: unsupported temporal format symbol '{c}'"
72 ))
73}
74
75fn supported_field<T>(field: Option<T>) -> Result<T> {
78 field.ok_or_else(invalid_pattern_character)
79}
80
81#[derive(Clone, Copy, Default)]
84struct PatternParts<'a> {
85 date: Option<NaiveDate>,
86 time: Option<NaiveTime>,
87 offset: Option<i32>,
88 zone: Option<&'a str>,
89}
90
91fn render_symbol(c: char, len: usize, parts: PatternParts<'_>) -> Result<String> {
98 let PatternParts {
99 date,
100 time,
101 offset,
102 zone,
103 } = parts;
104 let kind = FieldKind::from_letter(c).ok_or_else(|| invalid_pattern_symbol(c))?;
105 Ok(match kind {
106 FieldKind::Year | FieldKind::WeekYear => {
107 let d = supported_field(date)?;
108 let y = if c == 'Y' {
109 d.iso_week().year()
110 } else if c == 'y' && d.year() <= 0 {
111 1 - d.year()
112 } else {
113 d.year()
114 };
115 if len == 2 {
116 format!("{:02}", y.rem_euclid(100))
117 } else if y < 0 {
118 format!("-{:0len$}", y.unsigned_abs())
119 } else {
120 format!("{y:0len$}")
121 }
122 }
123 FieldKind::Month => {
124 let month = supported_field(date)?.month();
125 if len >= 3 {
126 let full = MONTH_NAMES[month as usize - 1];
127 match len {
129 3 => full.chars().take(3).collect(),
130 4 => full.to_string(),
131 5 => full
132 .chars()
133 .next()
134 .expect("month names are non-empty")
135 .to_string(),
136 _ => return Err(invalid_pattern_character()),
137 }
138 } else {
139 format!("{month:0len$}")
140 }
141 }
142 FieldKind::Quarter => {
143 let q = (supported_field(date)?.month0() / 3) + 1;
144 match len {
145 1 => q.to_string(),
146 2 => format!("{q:02}"),
147 3 => format!("Q{q}"),
148 4 => match q {
149 1 => "1st quarter".into(),
150 2 => "2nd quarter".into(),
151 3 => "3rd quarter".into(),
152 _ => "4th quarter".into(),
153 },
154 5 => q.to_string(),
155 _ => return Err(invalid_pattern_character()),
156 }
157 }
158 FieldKind::Day => {
159 if len > 2 {
160 return Err(invalid_pattern_character());
161 }
162 format!("{:0len$}", supported_field(date)?.day())
163 }
164 FieldKind::DayOfYear => format!("{:0len$}", supported_field(date)?.ordinal()),
165 FieldKind::DayOfWeekName => {
166 let weekday = supported_field(date)?.weekday();
167 let name = WEEKDAY_NAMES[weekday.num_days_from_monday() as usize];
168 if len >= 4 {
169 name.into()
170 } else {
171 name.chars().take(3).collect()
172 }
173 }
174 FieldKind::DayOfWeekNum => {
175 (supported_field(date)?.weekday().num_days_from_sunday() + 1).to_string()
176 }
177 FieldKind::Week => supported_field(date)?.iso_week().week().to_string(),
178 FieldKind::WeekOfMonth => {
179 let date = supported_field(date)?;
180 let first = date
181 .with_day(1)
182 .expect("every month has a first day")
183 .weekday()
184 .num_days_from_sunday();
185 ((date.day() + first - 1) / 7 + 1).to_string()
186 }
187 FieldKind::AlignedDayOfWeek => (supported_field(date)?.day0() / 7 + 1).to_string(),
188 FieldKind::ModifiedJulianDay => {
189 (supported_field(date)?.num_days_from_ce() - 678_576).to_string()
190 }
191 FieldKind::Era => {
192 if supported_field(date)?.year() <= 0 {
193 "BC".into()
194 } else {
195 "AD".into()
196 }
197 }
198 FieldKind::HourOfDay => format!("{:0len$}", supported_field(time)?.hour()),
199 FieldKind::ClockHour => {
200 let h = supported_field(time)?.hour();
201 format!("{:0len$}", if h == 0 { 24 } else { h })
202 }
203 FieldKind::HourOfAmPm if c == 'h' => {
204 let h = supported_field(time)?.hour() % 12;
205 format!("{:0len$}", if h == 0 { 12 } else { h })
206 }
207 FieldKind::HourOfAmPm => format!("{:0len$}", supported_field(time)?.hour() % 12),
208 FieldKind::AmPm => {
209 if supported_field(time)?.hour() < 12 {
210 "AM".into()
211 } else {
212 "PM".into()
213 }
214 }
215 FieldKind::PeriodOfDay => {
216 let hour = supported_field(time)?.hour();
217 match hour {
218 0..=5 => "at night",
219 6..=11 => "in the morning",
220 12..=17 => "in the afternoon",
221 _ => "in the evening",
222 }
223 .into()
224 }
225 FieldKind::Minute => format!("{:0len$}", supported_field(time)?.minute()),
226 FieldKind::Second => format!("{:0len$}", supported_field(time)?.second()),
227 FieldKind::Fraction => {
228 let nanos = supported_field(time)?.nanosecond();
229 let width = fraction_width(len)?;
230 format!("{nanos:09}").chars().take(width).collect()
231 }
232 FieldKind::NanoOfSecond => supported_field(time)?.nanosecond().to_string(),
233 FieldKind::NanoOfDay => time_to_nanos(supported_field(time)?).to_string(),
234 FieldKind::MilliOfDay => (time_to_nanos(supported_field(time)?) / 1_000_000).to_string(),
235 FieldKind::OffsetZ => {
236 let offset = supported_field(offset)?;
237 match len {
238 1..=3 => format_offset(offset).replace(':', ""),
239 4 if offset == 0 => "GMT".into(),
240 4 => format!("GMT{}", format_offset(offset)),
241 5 => format_zone_offset(offset),
242 _ => return Err(invalid_pattern_character()),
243 }
244 }
245 FieldKind::OffsetFractional => {
246 let offset = supported_field(offset)?;
247 if offset == 0 && c == 'X' {
248 "Z".into()
249 } else {
250 let raw = format_offset(offset);
251 let compact = raw.replace(':', "");
252 match len {
253 1 => {
254 if offset % 3600 == 0 {
255 compact[..3].into()
256 } else {
257 compact
258 }
259 }
260 2 | 4 => compact,
261 3 | 5 => raw,
262 _ => return Err(invalid_pattern_character()),
263 }
264 }
265 }
266 FieldKind::OffsetLocalized => {
267 let offset = supported_field(offset)?;
268 match (len, offset) {
269 (1 | 4, 0) => "GMT".into(),
270 (1, _) if offset % 3600 == 0 => {
271 format!("GMT{:+}", offset / 3600)
272 }
273 (1, _) => format!("GMT{}", format_offset(offset)),
274 (4, _) => format!("GMT{}", format_offset(offset)),
275 _ => return Err(invalid_pattern_character()),
276 }
277 }
278 FieldKind::ZoneId if c == 'V' && len == 2 => supported_field(zone)?.to_string(),
282 FieldKind::ZoneId if c == 'V' => return Err(invalid_pattern_symbol(c)),
283 FieldKind::ZoneName | FieldKind::ZoneId => {
286 let zone = supported_field(zone)?;
287 if (c == 'z' && len > 4) || (c == 'v' && !matches!(len, 1 | 4)) {
288 return Err(invalid_pattern_character());
289 }
290 match (zone_display(zone), c, len) {
291 (Some(d), 'z', 4) => d.long_summer.into(),
292 (Some(d), 'v', 4) => d.long_generic.into(),
293 (Some(d), 'z', _) => d.short_summer.into(),
294 (Some(d), _, _) => d.short_generic.into(),
295 (None, ..) => zone.into(),
296 }
297 }
298 })
299}
300
301pub fn format_pattern(value: &Temporal, pattern: &str) -> Result<String> {
306 if pattern.chars().any(|c| matches!(c, '#' | '{' | '}')) {
307 return Err(invalid_pattern_character());
308 }
309 let parts = match value {
310 Temporal::Date(d) => PatternParts {
311 date: Some(*d),
312 ..Default::default()
313 },
314 Temporal::LocalTime(t) => PatternParts {
315 time: Some(*t),
316 ..Default::default()
317 },
318 Temporal::Time { time, offset } => PatternParts {
319 time: Some(*time),
320 offset: Some(*offset),
321 ..Default::default()
322 },
323 Temporal::LocalDateTime(dt) => PatternParts {
324 date: Some(dt.date()),
325 time: Some(dt.time()),
326 ..Default::default()
327 },
328 Temporal::DateTime { utc, offset, zone } => {
329 let local = add_offset(*utc, *offset)?;
330 PatternParts {
331 date: Some(local.date()),
332 time: Some(local.time()),
333 offset: Some(*offset),
334 zone: zone.as_deref(),
335 }
336 }
337 Temporal::Duration {
338 months,
339 days,
340 nanos,
341 } => return format_duration_pattern(*months, *days, *nanos, pattern),
342 Temporal::CivilDate { .. } | Temporal::CivilDateTime { .. } => {
343 return if pattern.is_empty() {
344 Ok(String::new())
345 } else {
346 Err(Error::ty(
347 "format pattern is unsupported for out-of-range dates",
348 ))
349 }
350 }
351 };
352 let chars: Vec<char> = pattern.chars().collect();
353 let mut out = String::new();
354 let mut i = 0;
355 let mut quoted = false;
356 while i < chars.len() {
357 if chars[i] == '\'' {
358 if chars.get(i + 1) == Some(&'\'') {
359 out.push('\'');
360 i += 2;
361 continue;
362 }
363 quoted = !quoted;
364 i += 1;
365 continue;
366 }
367 if !quoted && matches!(chars[i], '[' | ']') {
368 i += 1;
369 continue;
370 }
371 if quoted || !chars[i].is_ascii_alphabetic() {
372 out.push(chars[i]);
373 i += 1;
374 continue;
375 }
376 let c = chars[i];
377 let mut len = 1;
378 while chars.get(i + len) == Some(&c) {
379 len += 1;
380 }
381 if c == 'p' {
382 let Some(&next) = chars.get(i + len) else {
383 return Err(invalid_pattern_character());
384 };
385 let mut next_len = 1;
386 while chars.get(i + len + next_len) == Some(&next) {
387 next_len += 1;
388 }
389 let rendered = format_pattern(value, &next.to_string().repeat(next_len))?;
390 out.push_str(&format!("{rendered:>len$}"));
391 i += len + next_len;
392 continue;
393 }
394 let piece = render_symbol(c, len, parts)?;
395 out.push_str(&piece);
396 i += len;
397 }
398 if quoted {
399 return Err(Error::syntax("unterminated quote in temporal format"));
402 }
403 Ok(out)
404}