jiff/fmt/mod.rs
1/*!
2Configurable support for printing and parsing datetimes and durations.
3
4Note that for most use cases, you should be using the corresponding
5[`Display`](std::fmt::Display) or [`FromStr`](std::str::FromStr) trait
6implementations for printing and parsing respectively. The APIs in this module
7provide more configurable support for printing and parsing.
8
9# Tables of examples
10
11The tables below attempt to show some examples of datetime and duration
12formatting, along with names and links to relevant routines and types. The
13point of these tables is to give a general overview of the formatting and
14parsing functionality in these sub-modules.
15
16## Support for `FromStr` and `Display`
17
18This table lists the formats supported by the [`FromStr`] and [`Display`]
19trait implementations on the datetime and duration types in Jiff.
20
21In all of these cases, the trait implementations are mere conveniences for
22functionality provided by the [`temporal`] sub-module (and, in a couple cases,
23the [`friendly`] sub-module). The sub-modules provide lower level control
24(such as parsing from `&[u8]`) and more configuration (such as controlling the
25disambiguation strategy used when parsing zoned datetime [RFC-9557] strings).
26
27There is substantial overlap between [RFC-3339], [RFC-9557] and [ISO-8601].
28The table below lists the most precise specification. For example,
29`2025-08-20T17:35:00-05` is valid in all three specifications, but is most
30precisely described by RFC 3339.
31
32| Example | Format | Links |
33| ------- | ------ | ----- |
34| `2025-08-20T17:35:00Z` | [RFC-3339] | [`Timestamp`] |
35| `2025-08-20T17:35:00-05` | [RFC-3339] | [`FromStr`] impl and<br>[`Timestamp::display_with_offset`] |
36| `2025-08-20T17:35:00+02[Poland]` | [RFC-9557] | [`ZonedDateTime`] |
37| `2025-08-20T17:35:00+02:00[+02:00]` | [RFC-9557] | [`ZonedDateTime`] |
38| `2025-08-20T17:35:00` | [ISO-8601] | [`civil::DateTime`] |
39| `2025-08-20` | [ISO-8601] | [`civil::Date`] |
40| `17:35:00` | [ISO-8601] | [`civil::Time`] |
41| `P1Y2M3W4DT5H6M7S` | [ISO-8601], [Temporal] | [`Span`] |
42| `PT1H2M3S` | [ISO-8601] | [`SignedDuration`], [`Span`] |
43| `PT1H2M3.123456789S` | [ISO-8601] | [`SignedDuration`], [`Span`] |
44| `1d 2h 3m 5s` | [`friendly`] | [`FromStr`] impl and alternative [`Display`]<br>via `{:#}` for [`SignedDuration`], [`Span`] |
45
46Note that for datetimes like `2025-08-20T17:35:00`, the following variants are
47also accepted:
48
49```text
502025-08-20 17:35:00
512025-08-20T17:35:00.123456789
522025-08-20T17:35
532025-08-20T17
54```
55
56This applies to RFC 3339 and RFC 9557 timestamps as well.
57
58Also, for ISO 8601 durations, the unit designator labels are matched
59case insensitively. For example, `PT1h2m3s` is recognized by Jiff.
60
61## The "friendly" duration format
62
63This table lists a few examples of the [`friendly`] duration format. Briefly,
64it is a bespoke format for Jiff, but is meant to match similar bespoke formats
65used elsewhere and be easier to read than the standard ISO 8601 duration
66format.
67
68All examples below can be parsed via a [`Span`]'s [`FromStr`] trait
69implementation. All examples with units no bigger than hours can be parsed via
70a [`SignedDuration`]'s [`FromStr`] trait implementation. This table otherwise
71shows the options for printing durations in the format shown.
72
73| Example | Print configuration |
74| ------- | ------------------- |
75| `1year 2months` | [`Designator::Verbose`] via [`SpanPrinter::designator`] |
76| `1yr 2mos` | [`Designator::Short`] via [`SpanPrinter::designator`] |
77| `1y 2mo` | [`Designator::Compact`] via [`SpanPrinter::designator`] (default) |
78| `1h2m3s` | [`Spacing::None`] via [`SpanPrinter::spacing`] |
79| `1h 2m 3s` | [`Spacing::BetweenUnits`] via [`SpanPrinter::spacing`] (default) |
80| `1 h 2 m 3 s` | [`Spacing::BetweenUnitsAndDesignators`] via [`SpanPrinter::spacing`] |
81| `2d 3h ago` | [`Direction::Auto`] via [`SpanPrinter::direction`] (default) |
82| `-2d 3h` | [`Direction::Sign`] via [`SpanPrinter::direction`] |
83| `+2d 3h` | [`Direction::ForceSign`] via [`SpanPrinter::direction`] |
84| `2d 3h ago` | [`Direction::Suffix`] via [`SpanPrinter::direction`] |
85| `9.123456789s` | [`FractionalUnit::Second`] via [`SpanPrinter::fractional`] |
86| `1y, 2mo` | [`SpanPrinter::comma_after_designator`] |
87| `15d 02:59:15.123` | [`SpanPrinter::hours_minutes_seconds`] |
88
89## Bespoke datetime formats via `strptime` and `strftime`
90
91Every datetime type has bespoke formatting routines defined on it. For example,
92[`ZonedDateTime::strptime`] and [`civil::Date::strftime`]. Additionally, the
93[`strtime`] sub-module also provides convenience routines, [`strtime::format`]
94and [`strtime::parse`], where the former is generic over any datetime type in
95Jiff and the latter provides a [`BrokenDownTime`] for granular parsing.
96
97| Example | Format string |
98| ------- | ------------- |
99| `2025-05-20` | `%Y-%m-%d` |
100| `2025-05-20` | `%F` |
101| `2025-W21-2` | `%G-W%V-%u` |
102| `05/20/25` | `%m/%d/%y` |
103| `Monday, February 10, 2025 at 9:01pm -0500` | `%A, %B %d, %Y at %-I:%M%P %z` |
104| `Monday, February 10, 2025 at 9:01pm EST` | `%A, %B %d, %Y at %-I:%M%P %Z` |
105| `Monday, February 10, 2025 at 9:01pm America/New_York` | `%A, %B %d, %Y at %-I:%M%P %Q` |
106
107The specific conversion specifiers supported are documented in the [`strtime`]
108sub-module. While precise POSIX compatibility is not guaranteed, the conversion
109specifiers are generally meant to match prevailing implementations. (Although
110there are many such implementations and they each tend to have their own quirks
111and features.)
112
113## RFC 2822 parsing and printing
114
115[RFC-2822] support is provided by the [`rfc2822`] sub-module.
116
117| Example | Links |
118| ------- | ----- |
119| `Thu, 29 Feb 2024 05:34 -0500` | [`rfc2822::parse`] and [`rfc2822::to_string`] |
120| `Thu, 01 Jan 1970 00:00:01 GMT` | [`DateTimePrinter::timestamp_to_rfc9110_string`] |
121
122[Temporal]: https://tc39.es/proposal-temporal/#sec-temporal-iso8601grammar
123[ISO-8601]: https://www.iso.org/iso-8601-date-and-time-format.html
124[RFC-3339]: https://www.rfc-editor.org/rfc/rfc3339
125[RFC-9557]: https://www.rfc-editor.org/rfc/rfc9557.html
126[ISO-8601]: https://www.iso.org/iso-8601-date-and-time-format.html
127[RFC-2822]: https://datatracker.ietf.org/doc/html/rfc2822
128[RFC-9110]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.7-15
129[`Display`]: std::fmt::Display
130[`FromStr`]: std::str::FromStr
131[`friendly`]: crate::fmt::friendly
132[`temporal`]: crate::fmt::temporal
133[`rfc2822`]: crate::fmt::rfc2822
134[`strtime`]: crate::fmt::strtime
135[`civil::DateTime`]: crate::civil::DateTime
136[`civil::Date`]: crate::civil::Date
137[`civil::Date::strftime`]: crate::civil::Date::strftime
138[`civil::Time`]: crate::civil::Time
139[`SignedDuration`]: crate::SignedDuration
140[`Span`]: crate::Span
141[`Timestamp`]: crate::Timestamp
142[`Timestamp::display_with_offset`]: crate::Timestamp::display_with_offset
143[`ZonedDateTime`]: crate::ZonedDateTime
144[`ZonedDateTime::strptime`]: crate::ZonedDateTime::strptime
145
146[`Designator::Verbose`]: crate::fmt::friendly::Designator::Verbose
147[`Designator::Short`]: crate::fmt::friendly::Designator::Short
148[`Designator::Compact`]: crate::fmt::friendly::Designator::Compact
149[`Spacing::None`]: crate::fmt::friendly::Spacing::None
150[`Spacing::BetweenUnits`]: crate::fmt::friendly::Spacing::BetweenUnits
151[`Spacing::BetweenUnitsAndDesignators`]: crate::fmt::friendly::Spacing::BetweenUnitsAndDesignators
152[`Direction::Auto`]: crate::fmt::friendly::Direction::Auto
153[`Direction::Sign`]: crate::fmt::friendly::Direction::Sign
154[`Direction::ForceSign`]: crate::fmt::friendly::Direction::ForceSign
155[`Direction::Suffix`]: crate::fmt::friendly::Direction::Suffix
156[`FractionalUnit::Second`]: crate::fmt::friendly::FractionalUnit::Second
157[`SpanPrinter::designator`]: crate::fmt::friendly::SpanPrinter::designator
158[`SpanPrinter::spacing`]: crate::fmt::friendly::SpanPrinter::spacing
159[`SpanPrinter::direction`]: crate::fmt::friendly::SpanPrinter::direction
160[`SpanPrinter::fractional`]: crate::fmt::friendly::SpanPrinter::fractional
161[`SpanPrinter::comma_after_designator`]: crate::fmt::friendly::SpanPrinter::comma_after_designator
162[`SpanPrinter::hours_minutes_seconds`]: crate::fmt::friendly::SpanPrinter::hours_minutes_seconds
163
164[`BrokenDownTime`]: crate::fmt::strtime::BrokenDownTime
165[`strtime::parse`]: crate::fmt::strtime::parse
166[`strtime::format`]: crate::fmt::strtime::format
167
168[`rfc2822::parse`]: crate::fmt::rfc2822::parse
169[`rfc2822::to_string`]: crate::fmt::rfc2822::to_string
170[`DateTimePrinter::timestamp_to_rfc9110_string`]: crate::fmt::rfc2822::DateTimePrinter::timestamp_to_rfc9110_string
171*/
172
173use crate::{
174 error::{Error, fmt::Error as E},
175 util::escape,
176};
177
178mod buffer;
179pub mod friendly;
180mod offset;
181pub mod rfc2822;
182mod rfc9557;
183#[cfg(feature = "serde")]
184pub mod serde;
185pub mod strtime;
186pub mod temporal;
187mod util;
188
189/// The result of parsing a value out of a slice of bytes.
190///
191/// This contains both the parsed value and the offset at which the value
192/// ended in the input given. This makes it possible to parse, for example, a
193/// datetime value as a prefix of some larger string without knowing ahead of
194/// time where it ends.
195#[derive(Clone)]
196pub(crate) struct Parsed<'i, V> {
197 /// The value parsed.
198 value: V,
199 /// The remaining unparsed input.
200 input: &'i [u8],
201}
202
203impl<'i, V> Parsed<'i, V> {
204 #[inline]
205 fn and_then<U>(
206 self,
207 map: impl FnOnce(V) -> Result<U, Error>,
208 ) -> Result<Parsed<'i, U>, Error> {
209 let Parsed { value, input } = self;
210 Ok(Parsed { value: map(value)?, input })
211 }
212}
213
214impl<'i, V: core::fmt::Display> Parsed<'i, V> {
215 /// Ensures that the parsed value represents the entire input. This occurs
216 /// precisely when the `input` on this parsed value is empty.
217 ///
218 /// This is useful when one expects a parsed value to consume the entire
219 /// input, and to consider it an error if it doesn't.
220 #[inline]
221 fn into_full(self) -> Result<V, Error> {
222 if self.input.is_empty() {
223 return Ok(self.value);
224 }
225 Err(Error::from(E::into_full_error(&self.value, self.input)))
226 }
227}
228
229impl<'i, V> Parsed<'i, V> {
230 /// Ensures that the parsed value represents the entire input. This occurs
231 /// precisely when the `input` on this parsed value is empty.
232 ///
233 /// This is useful when one expects a parsed value to consume the entire
234 /// input, and to consider it an error if it doesn't.
235 ///
236 /// This is like `Parsed::into_full`, but lets the caller provide a custom
237 /// `Display` implementation.
238 #[inline]
239 fn into_full_with(
240 self,
241 display: impl core::fmt::Display,
242 ) -> Result<V, Error> {
243 if self.input.is_empty() {
244 return Ok(self.value);
245 }
246 Err(Error::from(E::into_full_error(&display, self.input)))
247 }
248}
249
250impl<'i, V: core::fmt::Debug> core::fmt::Debug for Parsed<'i, V> {
251 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
252 f.debug_struct("Parsed")
253 .field("value", &self.value)
254 .field("input", &escape::Bytes(self.input))
255 .finish()
256 }
257}
258
259/// A trait for printing datetimes or spans into Unicode-accepting buffers or
260/// streams.
261///
262/// The most useful implementations of this trait are for the `String` and
263/// `Vec<u8>` types. But any implementation of [`std::fmt::Write`] and
264/// [`std::io::Write`] can be used via the [`StdFmtWrite`] and [`StdIoWrite`]
265/// adapters, respectively.
266///
267/// Most users of Jiff should not need to interact with this trait directly.
268/// Instead, printing is handled via the [`Display`](std::fmt::Display)
269/// implementation of the relevant type.
270///
271/// # Design
272///
273/// This trait is a near-clone of the `std::fmt::Write` trait. It's also very
274/// similar to the `std::io::Write` trait, but like `std::fmt::Write`, this
275/// trait is limited to writing valid UTF-8. The UTF-8 restriction was adopted
276/// because we really want to support printing datetimes and spans to `String`
277/// buffers. If we permitted writing `&[u8]` data, then writing to a `String`
278/// buffer would always require a costly UTF-8 validation check.
279///
280/// The `std::fmt::Write` trait wasn't used itself because:
281///
282/// 1. Using a custom trait allows us to require using Jiff's error type.
283/// (Although this extra flexibility isn't currently used much, since printing
284/// rarely fails for any reason other than the underlying `jiff::fmt::Write`
285/// implementation failing.)
286/// 2. Using a custom trait allows us more control over the implementations of
287/// the trait. For example, a custom trait means we can format directly into
288/// a `Vec<u8>` buffer, which isn't possible with `std::fmt::Write` because
289/// there is no `std::fmt::Write` trait implementation for `Vec<u8>`.
290pub trait Write {
291 /// Write the given string to this writer, returning whether the write
292 /// succeeded or not.
293 fn write_str(&mut self, string: &str) -> Result<(), Error>;
294
295 /// Write the given character to this writer, returning whether the write
296 /// succeeded or not.
297 #[inline]
298 fn write_char(&mut self, char: char) -> Result<(), Error> {
299 self.write_str(char.encode_utf8(&mut [0; 4]))
300 }
301
302 /// Returns a `Vec<u8>` backing store for this implementation.
303 ///
304 /// Consumers of this trait may call this method to get a view directly
305 /// into a buffer for more optimized writing.
306 ///
307 /// The default implementation always returns `None`.
308 ///
309 /// This method is only available when Jiff's `alloc` feature is enabled.
310 ///
311 /// # Safety
312 ///
313 /// Callers must ensure that only valid UTF-8 is written to the buffer
314 /// returned.
315 #[cfg(feature = "alloc")]
316 #[inline]
317 unsafe fn as_mut_vec(&mut self) -> Option<&mut alloc::vec::Vec<u8>> {
318 None
319 }
320}
321
322#[cfg(any(test, feature = "alloc"))]
323impl Write for alloc::string::String {
324 #[inline]
325 fn write_str(&mut self, string: &str) -> Result<(), Error> {
326 self.push_str(string);
327 Ok(())
328 }
329
330 #[cfg(feature = "alloc")]
331 #[inline]
332 unsafe fn as_mut_vec(&mut self) -> Option<&mut alloc::vec::Vec<u8>> {
333 // SAFETY: The conditions are forwarded to the trait interface.
334 unsafe { Some(alloc::string::String::as_mut_vec(self)) }
335 }
336}
337
338#[cfg(any(test, feature = "alloc"))]
339impl Write for alloc::vec::Vec<u8> {
340 #[inline]
341 fn write_str(&mut self, string: &str) -> Result<(), Error> {
342 self.extend_from_slice(string.as_bytes());
343 Ok(())
344 }
345
346 #[cfg(feature = "alloc")]
347 #[inline]
348 unsafe fn as_mut_vec(&mut self) -> Option<&mut alloc::vec::Vec<u8>> {
349 Some(self)
350 }
351}
352
353impl<W: Write> Write for &mut W {
354 fn write_str(&mut self, string: &str) -> Result<(), Error> {
355 (**self).write_str(string)
356 }
357
358 #[inline]
359 fn write_char(&mut self, char: char) -> Result<(), Error> {
360 (**self).write_char(char)
361 }
362
363 #[cfg(feature = "alloc")]
364 #[inline]
365 unsafe fn as_mut_vec(&mut self) -> Option<&mut alloc::vec::Vec<u8>> {
366 // SAFETY: The conditions are forwarded to the trait interface.
367 unsafe { (**self).as_mut_vec() }
368 }
369}
370
371impl Write for &mut dyn Write {
372 fn write_str(&mut self, string: &str) -> Result<(), Error> {
373 (**self).write_str(string)
374 }
375
376 #[inline]
377 fn write_char(&mut self, char: char) -> Result<(), Error> {
378 (**self).write_char(char)
379 }
380
381 #[cfg(feature = "alloc")]
382 #[inline]
383 unsafe fn as_mut_vec(&mut self) -> Option<&mut alloc::vec::Vec<u8>> {
384 // SAFETY: The conditions are forwarded to the trait interface.
385 unsafe { (**self).as_mut_vec() }
386 }
387}
388
389/// An adapter for using `std::io::Write` implementations with `fmt::Write`.
390///
391/// This is useful when one wants to format a datetime or span directly
392/// to something with a `std::io::Write` trait implementation but not a
393/// `fmt::Write` implementation.
394///
395/// # Example
396///
397/// ```no_run
398/// use std::{fs::File, io::{BufWriter, Write}, path::Path};
399///
400/// use jiff::{civil::date, fmt::{StdIoWrite, temporal::DateTimePrinter}};
401///
402/// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("America/New_York")?;
403///
404/// let path = Path::new("/tmp/output");
405/// let mut file = BufWriter::new(File::create(path)?);
406/// DateTimePrinter::new()
407/// .print_zoned_datetime(&zdt, StdIoWrite(&mut file))
408/// .unwrap();
409/// file.flush()?;
410/// assert_eq!(
411/// std::fs::read_to_string(path)?,
412/// "2024-06-15T07:00:00-04:00[America/New_York]",
413/// );
414///
415/// # Ok::<(), Box<dyn std::error::Error>>(())
416/// ```
417#[cfg(feature = "std")]
418#[derive(Clone, Debug)]
419pub struct StdIoWrite<W>(pub W);
420
421#[cfg(feature = "std")]
422impl<W: std::io::Write> Write for StdIoWrite<W> {
423 #[inline]
424 fn write_str(&mut self, string: &str) -> Result<(), Error> {
425 self.0.write_all(string.as_bytes()).map_err(Error::io)
426 }
427}
428
429/// An adapter for using `std::fmt::Write` implementations with `fmt::Write`.
430///
431/// This is useful when one wants to format a datetime or span directly
432/// to something with a `std::fmt::Write` trait implementation but not a
433/// `fmt::Write` implementation.
434///
435/// (Despite using `Std` in this name, this type is available in `core`-only
436/// configurations.)
437///
438/// # Example
439///
440/// This example shows the `std::fmt::Display` trait implementation for
441/// [`civil::DateTime`](crate::civil::DateTime) (but using a wrapper type).
442///
443/// ```
444/// use jiff::{civil::DateTime, fmt::{temporal::DateTimePrinter, StdFmtWrite}};
445///
446/// struct MyDateTime(DateTime);
447///
448/// impl std::fmt::Display for MyDateTime {
449/// fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
450///
451/// static P: DateTimePrinter = DateTimePrinter::new();
452/// P.print_datetime(&self.0, StdFmtWrite(f))
453/// .map_err(|_| std::fmt::Error)
454/// }
455/// }
456///
457/// let dt = MyDateTime(DateTime::constant(2024, 6, 15, 17, 30, 0, 0));
458/// assert_eq!(dt.to_string(), "2024-06-15T17:30:00");
459/// ```
460#[derive(Clone, Debug)]
461pub struct StdFmtWrite<W>(pub W);
462
463impl<W: core::fmt::Write> Write for StdFmtWrite<W> {
464 #[inline]
465 fn write_str(&mut self, string: &str) -> Result<(), Error> {
466 self.0
467 .write_str(string)
468 .map_err(|_| Error::from(E::StdFmtWriteAdapter))
469 }
470}
471
472impl<W: Write> core::fmt::Write for StdFmtWrite<W> {
473 #[inline]
474 fn write_str(&mut self, string: &str) -> Result<(), core::fmt::Error> {
475 self.0.write_str(string).map_err(|_| core::fmt::Error)
476 }
477}
478
479/// An adapter for writing Jiff's formatted output to a
480/// [`defmt`] formatter.
481///
482/// This is used by Jiff's [`defmt::Format`] trait implementations to share the
483/// same printer code used for [`core::fmt`] output.
484///
485/// # Example
486///
487/// This example shows the [`defmt::Format`] trait implementation for
488/// [`civil::DateTime`](crate::civil::DateTime) (but using a wrapper type).
489///
490/// ```
491/// use jiff::{
492/// civil::DateTime,
493/// fmt::{temporal::DateTimePrinter, DefmtWrite},
494/// };
495///
496/// struct MyDateTime(DateTime);
497///
498/// impl defmt::Format for MyDateTime {
499/// fn format(&self, f: defmt::Formatter) {
500/// static P: DateTimePrinter = DateTimePrinter::new();
501/// defmt::unwrap!(P.print_datetime(&self.0, DefmtWrite(f)));
502/// }
503/// }
504/// ```
505#[cfg(feature = "defmt")]
506#[derive(defmt::Format)]
507pub struct DefmtWrite<'a>(pub defmt::Formatter<'a>);
508
509#[cfg(feature = "defmt")]
510impl<'a> core::fmt::Debug for DefmtWrite<'a> {
511 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
512 f.debug_struct("DefmtWrite").finish()
513 }
514}
515
516#[cfg(feature = "defmt")]
517impl<'a> core::fmt::Write for DefmtWrite<'a> {
518 #[inline]
519 fn write_str(&mut self, string: &str) -> Result<(), core::fmt::Error> {
520 defmt::write!(self.0, "{=str}", string);
521 Ok(())
522 }
523}
524
525#[cfg(feature = "defmt")]
526impl<'a> Write for DefmtWrite<'a> {
527 #[inline]
528 fn write_str(&mut self, string: &str) -> Result<(), Error> {
529 defmt::write!(self.0, "{=str}", string);
530 Ok(())
531 }
532}