jiff/fmt/strtime/mod.rs
1/*!
2Support for "printf"-style parsing and formatting.
3
4While the routines exposed in this module very closely resemble the
5corresponding [`strptime`] and [`strftime`] POSIX functions, it is not a goal
6for the formatting machinery to precisely match POSIX semantics.
7
8If there is a conversion specifier you need that Jiff doesn't support, please
9[create a new issue][create-issue].
10
11The formatting and parsing in this module does not currently support any
12form of localization. Please see [this issue][locale] about the topic of
13localization in Jiff.
14
15[create-issue]: https://github.com/BurntSushi/jiff/issues/new
16[locale]: https://github.com/BurntSushi/jiff/issues/4
17
18# Example
19
20This shows how to parse a civil date and its weekday:
21
22```
23use jiff::civil::Date;
24
25let date = Date::strptime("%Y-%m-%d is a %A", "2024-07-15 is a Monday")?;
26assert_eq!(date.to_string(), "2024-07-15");
27// Leading zeros are optional for numbers in all cases:
28let date = Date::strptime("%Y-%m-%d is a %A", "2024-07-15 is a Monday")?;
29assert_eq!(date.to_string(), "2024-07-15");
30// Parsing does error checking! 2024-07-15 was not a Tuesday.
31assert!(Date::strptime("%Y-%m-%d is a %A", "2024-07-15 is a Tuesday").is_err());
32
33# Ok::<(), Box<dyn std::error::Error>>(())
34```
35
36And this shows how to format a zoned datetime with a time zone abbreviation:
37
38```
39use jiff::civil::date;
40
41let zdt = date(2024, 7, 15).at(17, 30, 59, 0).in_tz("Australia/Hobart")?;
42// %-I instead of %I means no padding.
43let string = zdt.strftime("%A, %B %d, %Y at %-I:%M%P %Z").to_string();
44assert_eq!(string, "Monday, July 15, 2024 at 5:30pm AEST");
45
46# Ok::<(), Box<dyn std::error::Error>>(())
47```
48
49Or parse a zoned datetime with an IANA time zone identifier:
50
51```
52use jiff::{civil::date, ZonedDateTime};
53
54let zdt = ZonedDateTime::strptime(
55 "%A, %B %d, %Y at %-I:%M%P %:Q",
56 "Monday, July 15, 2024 at 5:30pm Australia/Hobart",
57)?;
58assert_eq!(
59 zdt,
60 date(2024, 7, 15).at(17, 30, 0, 0).in_tz("Australia/Hobart")?,
61);
62
63# Ok::<(), Box<dyn std::error::Error>>(())
64```
65
66# Usage
67
68For most cases, you can use the `strptime` and `strftime` methods on the
69corresponding datetime type. For example, [`ZonedDateTime::strptime`] and
70[`ZonedDateTime::strftime`]. However, the [`BrokenDownTime`] type in this
71module provides a little more control.
72
73For example, assuming `t` is a `civil::Time`, then
74`t.strftime("%Y").to_string()` will actually panic because a `civil::Time` does
75not have a year. While the underlying formatting machinery actually returns
76an error, this error gets turned into a panic by virtue of going through the
77`std::fmt::Display` and `std::string::ToString` APIs.
78
79In contrast, [`BrokenDownTime::format`] (or just [`format`](format())) can
80report the error to you without any panicking:
81
82```
83use jiff::{civil::time, fmt::strtime};
84
85let t = time(23, 59, 59, 0);
86assert_eq!(
87 strtime::format("%Y", t).unwrap_err().to_string(),
88 "strftime formatting failed: %Y failed: requires date to format",
89);
90```
91
92# Advice
93
94The formatting machinery supported by this module is not especially expressive.
95The pattern language is a simple sequence of conversion specifiers interspersed
96by literals and arbitrary whitespace. This means that you sometimes need
97delimiters or spaces between components. For example, this is fine:
98
99```
100use jiff::fmt::strtime;
101
102let date = strtime::parse("%Y%m%d", "20240715")?.to_date()?;
103assert_eq!(date.to_string(), "2024-07-15");
104# Ok::<(), Box<dyn std::error::Error>>(())
105```
106
107But this is ambiguous (is the year `999` or `9990`?):
108
109```
110use jiff::fmt::strtime;
111
112assert!(strtime::parse("%Y%m%d", "9990715").is_err());
113```
114
115In this case, since years greedily consume up to 4 digits by default, `9990`
116is parsed as the year. And since months greedily consume up to 2 digits by
117default, `71` is parsed as the month, which results in an invalid day. If you
118expect your datetimes to always use 4 digits for the year, then it might be
119okay to skip on the delimiters. For example, the year `999` could be written
120with a leading zero:
121
122```
123use jiff::fmt::strtime;
124
125let date = strtime::parse("%Y%m%d", "09990715")?.to_date()?;
126assert_eq!(date.to_string(), "0999-07-15");
127// Indeed, the leading zero is written by default when
128// formatting, since years are padded out to 4 digits
129// by default:
130assert_eq!(date.strftime("%Y%m%d").to_string(), "09990715");
131
132# Ok::<(), Box<dyn std::error::Error>>(())
133```
134
135The main advice here is that these APIs can come in handy for ad hoc tasks that
136would otherwise be annoying to deal with. For example, I once wrote a tool to
137extract data from an XML dump of my SMS messages, and one of the date formats
138used was `Apr 1, 2022 20:46:15`. That doesn't correspond to any standard, and
139while parsing it with a regex isn't that difficult, it's pretty annoying,
140especially because of the English abbreviated month name. That's exactly the
141kind of use case where this module shines.
142
143If the formatting machinery in this module isn't flexible enough for your use
144case and you don't control the format, it is recommended to write a bespoke
145parser (possibly with regex). It is unlikely that the expressiveness of this
146formatting machinery will be improved much. (Although it is plausible to add
147new conversion specifiers.)
148
149# Conversion specifications
150
151This table lists the complete set of conversion specifiers supported in the
152format. While most conversion specifiers are supported as is in both parsing
153and formatting, there are some differences. Where differences occur, they are
154noted in the table below.
155
156When parsing, and whenever a conversion specifier matches an enumeration of
157strings, the strings are matched without regard to ASCII case.
158
159| Specifier | Example | Description |
160| --------- | ------- | ----------- |
161| `%%` | `%%` | A literal `%`. |
162| `%A`, `%a` | `Sunday`, `Sun` | The full and abbreviated weekday, respectively. |
163| `%B`, `%b`, `%h` | `June`, `Jun`, `Jun` | The full and abbreviated month name, respectively. |
164| `%C` | `20` | The century of the year. No padding. |
165| `%c` | `2024 M07 14, Sun 17:31:59` | The date and clock time via [`Custom`]. Supported when formatting only. |
166| `%D` | `7/14/24` | Equivalent to `%m/%d/%y`. |
167| `%d`, `%e` | `25`, ` 5` | The day of the month. `%d` is zero-padded, `%e` is space padded. |
168| `%F` | `2024-07-14` | Equivalent to `%Y-%m-%d`. |
169| `%f` | `000456` | Fractional seconds, up to nanosecond precision. |
170| `%.f` | `.000456` | Optional fractional seconds, with dot, up to nanosecond precision. |
171| `%G` | `2024` | An [ISO 8601 week-based] year. Zero padded to 4 digits. |
172| `%g` | `24` | A two-digit [ISO 8601 week-based] year. Represents only 1969-2068. Zero padded. |
173| `%H` | `23` | The hour in a 24 hour clock. Zero padded. |
174| `%I` | `11` | The hour in a 12 hour clock. Zero padded. |
175| `%j` | `060` | The day of the year. Range is `1..=366`. Zero padded to 3 digits. |
176| `%k` | `15` | The hour in a 24 hour clock. Space padded. |
177| `%l` | ` 3` | The hour in a 12 hour clock. Space padded. |
178| `%M` | `04` | The minute. Zero padded. |
179| `%m` | `01` | The month. Zero padded. |
180| `%N` | `123456000` | Fractional seconds, up to nanosecond precision. Alias for `%9f`. |
181| `%n` | `\n` | Formats as a newline character. Parses arbitrary whitespace. |
182| `%P` | `am` | Whether the time is in the AM or PM, lowercase. |
183| `%p` | `PM` | Whether the time is in the AM or PM, uppercase. |
184| `%Q` | `America/New_York`, `+0530` | An IANA time zone identifier, or `%z` if one doesn't exist. |
185| `%:Q` | `America/New_York`, `+05:30` | An IANA time zone identifier, or `%:z` if one doesn't exist. |
186| `%q` | `4` | The quarter of the year. Supported when formatting only. |
187| `%R` | `23:30` | Equivalent to `%H:%M`. |
188| `%r` | `8:30:00 AM` | The 12-hour clock time via [`Custom`]. Supported when formatting only. |
189| `%S` | `59` | The second. Zero padded. |
190| `%s` | `1737396540` | A Unix timestamp, in seconds. |
191| `%T` | `23:30:59` | Equivalent to `%H:%M:%S`. |
192| `%t` | `\t` | Formats as a tab character. Parses arbitrary whitespace. |
193| `%U` | `03` | Week number. Week 1 is the first week starting with a Sunday. Zero padded. |
194| `%u` | `7` | The day of the week beginning with Monday at `1`. |
195| `%V` | `05` | Week number in the [ISO 8601 week-based] calendar. Zero padded. |
196| `%W` | `03` | Week number. Week 1 is the first week starting with a Monday. Zero padded. |
197| `%w` | `0` | The day of the week beginning with Sunday at `0`. |
198| `%X` | `17:31:59` | The clock time via [`Custom`]. Supported when formatting only. |
199| `%x` | `2024 M07 14` | The date via [`Custom`]. Supported when formatting only. |
200| `%Y` | `2024` | A full year, including century. Zero padded to 4 digits. |
201| `%y` | `24` | A two-digit year. Represents only 1969-2068. Zero padded. |
202| `%Z` | `EDT` | A time zone abbreviation. Supported when formatting only. |
203| `%z` | `+0530` | A time zone offset in the format `[+-]HHMM[SS]`. |
204| `%:z` | `+05:30` | A time zone offset in the format `[+-]HH:MM[:SS]`. |
205| `%::z` | `+05:30:00` | A time zone offset in the format `[+-]HH:MM:SS`. |
206| `%:::z` | `-04`, `+05:30` | A time zone offset in the format `[+-]HH:[MM[:SS]]`. |
207
208When formatting, the following flags can be inserted immediately after the `%`
209and before the directive:
210
211* `_` - Pad a numeric result to the left with spaces.
212* `-` - Do not pad a numeric result.
213* `0` - Pad a numeric result to the left with zeros.
214* `^` - Use alphabetic uppercase for all relevant strings.
215* `#` - Swap the case of the result string. This is typically only useful with
216`%p` or `%Z`, since they are the only conversion specifiers that emit strings
217entirely in uppercase by default.
218
219The above flags override the "default" settings of a specifier. For example,
220`%_d` pads with spaces instead of zeros, and `%0e` pads with zeros instead of
221spaces. The exceptions are the locale (`%c`, `%r`, `%X`, `%x`), and time zone
222(`%z`, `%:z`) specifiers. They are unaffected by any flags.
223
224Moreover, any number of decimal digits can be inserted after the (possibly
225absent) flag and before the directive, so long as the parsed number is less
226than 256. The number formed by these digits will correspond to the minimum
227amount of padding (to the left). Note that padding is clamped to a maximum of
228`20`.
229
230The flags and padding amount above may be used when parsing as well. Most
231settings are ignored during parsing except for padding. For example, if one
232wanted to parse `003` as the day `3`, then one should use `%03d`. Otherwise, by
233default, `%d` will only try to consume at most 2 digits.
234
235The `%f` and `%.f` flags also support specifying the precision, up to
236nanoseconds. For example, `%3f` and `%.3f` will both always print a fractional
237second component to exactly 3 decimal places. When no precision is specified,
238then `%f` will always emit at least one digit, even if it's zero. But `%.f`
239will emit the empty string when the fractional component is zero. Otherwise, it
240will include the leading `.`. For parsing, `%f` does not include the leading
241dot, but `%.f` does. Note that all of the options above are still parsed for
242`%f` and `%.f`, but they are all no-ops (except for the padding for `%f`, which
243is instead interpreted as a precision setting). When using a precision setting,
244truncation is used. If you need a different rounding mode, you should use
245higher level APIs like [`Timestamp::round`] or [`ZonedDateTime::round`].
246
247# Conditionally unsupported
248
249Jiff does not support `%Q` or `%:Q` (IANA time zone identifier) when the
250`alloc` crate feature is not enabled. This is because a time zone identifier
251is variable width data. If you have a use case for this, please
252[detail it in a new issue](https://github.com/BurntSushi/jiff/issues/new).
253
254# Unsupported
255
256The following things are currently unsupported:
257
258* Parsing or formatting fractional seconds in the time time zone offset.
259* The `%+` conversion specifier is not supported since there doesn't seem to
260 be any consistent definition for it.
261* With only Jiff, the `%c`, `%r`, `%X` and `%x` locale oriented specifiers
262 use a default "unknown" locale via the [`DefaultCustom`] implementation
263 of the [`Custom`] trait. An example of the default locale format for `%c`
264 is `2024 M07 14, Sun 17:31:59`. One can either switch the POSIX locale
265 via [`PosixCustom`] (e.g., `Sun Jul 14 17:31:59 2024`), or write your own
266 implementation of [`Custom`] powered by [`icu`] and glued together with Jiff
267 via [`jiff-icu`].
268* The `E` and `O` locale modifiers are not supported.
269
270[`strftime`]: https://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html
271[`strptime`]: https://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html
272[ISO 8601 week-based]: https://en.wikipedia.org/wiki/ISO_week_date
273[`icu`]: https://docs.rs/icu
274[`jiff-icu`]: https://docs.rs/jiff-icu
275*/
276
277use crate::{
278 Error, Timestamp, ZonedDateTime,
279 civil::{Date, DateTime, ISOWeekDate, Time, Weekday},
280 error::{ErrorContext, fmt::strtime::Error as E},
281 fmt::{
282 Write,
283 buffer::{ArrayBuffer, BorrowedWriter},
284 strtime::{parse::Parser, printer::Formatter},
285 },
286 tz::{Offset, OffsetConflict, TimeZone, TimeZoneDatabase},
287 util::{self, b, escape},
288};
289
290mod parse;
291mod printer;
292
293/// Parse the given `input` according to the given `format` string.
294///
295/// See the [module documentation](self) for details on what's supported.
296///
297/// This routine is the same as [`BrokenDownTime::parse`], but may be more
298/// convenient to call.
299///
300/// # Errors
301///
302/// This returns an error when parsing failed. This might happen because
303/// the format string itself was invalid, or because the input didn't match
304/// the format string.
305///
306/// # Example
307///
308/// This example shows how to parse something resembling a RFC 2822 datetime:
309///
310/// ```
311/// use jiff::{civil::date, fmt::strtime, tz};
312///
313/// let zdt = strtime::parse(
314/// "%a, %d %b %Y %T %z",
315/// "Mon, 15 Jul 2024 16:24:59 -0400",
316/// )?
317/// .to_zoned_datetime()?;
318///
319/// let tz = tz::offset(-4).to_time_zone();
320/// assert_eq!(
321/// zdt,
322/// date(2024, 7, 15).at(16, 24, 59, 0).to_zoned_datetime(tz)?
323/// );
324///
325/// # Ok::<(), Box<dyn std::error::Error>>(())
326/// ```
327///
328/// Of course, one should prefer using the [`fmt::rfc2822`](super::rfc2822)
329/// module, which contains a dedicated RFC 2822 parser. For example, the above
330/// format string does not part all valid RFC 2822 datetimes, since, e.g.,
331/// the leading weekday is optional and so are the seconds in the time, but
332/// `strptime`-like APIs have no way of expressing such requirements.
333///
334/// [RFC 2822]: https://datatracker.ietf.org/doc/html/rfc2822
335///
336/// # Example: parse RFC 3339 timestamp with fractional seconds
337///
338/// ```
339/// use jiff::{civil::date, fmt::strtime};
340///
341/// let zdt = strtime::parse(
342/// "%Y-%m-%dT%H:%M:%S%.f%:z",
343/// "2024-07-15T16:24:59.123456789-04:00",
344/// )?
345/// .to_zoned_datetime()?;
346/// assert_eq!(
347/// zdt,
348/// date(2024, 7, 15).at(16, 24, 59, 123_456_789).in_tz("America/New_York")?,
349/// );
350///
351/// # Ok::<(), Box<dyn std::error::Error>>(())
352/// ```
353#[inline]
354pub fn parse(
355 format: impl AsRef<[u8]>,
356 input: impl AsRef<[u8]>,
357) -> Result<BrokenDownTime, Error> {
358 BrokenDownTime::parse(format, input)
359}
360
361/// Format the given broken down time using the format string given.
362///
363/// See the [module documentation](self) for details on what's supported.
364///
365/// This routine is like [`BrokenDownTime::format`], but may be more
366/// convenient to call. Also, it returns a `String` instead of accepting a
367/// [`fmt::Write`](super::Write) trait implementation to write to.
368///
369/// Note that `broken_down_time` can be _anything_ that can be converted into
370/// it. This includes, for example, [`ZonedDateTime`], [`Timestamp`],
371/// [`DateTime`], [`Date`] and [`Time`].
372///
373/// # Errors
374///
375/// This returns an error when formatting failed. Formatting can fail either
376/// because of an invalid format string, or if formatting requires a field in
377/// `BrokenDownTime` to be set that isn't. For example, trying to format a
378/// [`DateTime`] with the `%z` specifier will fail because a `DateTime` has no
379/// time zone or offset information associated with it.
380///
381/// # Example
382///
383/// This example shows how to format a `ZonedDateTime` into something
384/// resembling a RFC 2822 datetime:
385///
386/// ```
387/// use jiff::{civil::date, fmt::strtime};
388///
389/// let zdt = date(2024, 7, 15).at(16, 24, 59, 0).in_tz("America/New_York")?;
390/// let string = strtime::format("%a, %-d %b %Y %T %z", &zdt)?;
391/// assert_eq!(string, "Mon, 15 Jul 2024 16:24:59 -0400");
392///
393/// # Ok::<(), Box<dyn std::error::Error>>(())
394/// ```
395///
396/// Of course, one should prefer using the [`fmt::rfc2822`](super::rfc2822)
397/// module, which contains a dedicated RFC 2822 printer.
398///
399/// [RFC 2822]: https://datatracker.ietf.org/doc/html/rfc2822
400///
401/// # Example: `date`-like output
402///
403/// While the output of the Unix `date` command is likely locale specific,
404/// this is what it looks like on my system:
405///
406/// ```
407/// use jiff::{civil::date, fmt::strtime};
408///
409/// let zdt = date(2024, 7, 15).at(16, 24, 59, 0).in_tz("America/New_York")?;
410/// let string = strtime::format("%a %b %e %I:%M:%S %p %Z %Y", &zdt)?;
411/// assert_eq!(string, "Mon Jul 15 04:24:59 PM EDT 2024");
412///
413/// # Ok::<(), Box<dyn std::error::Error>>(())
414/// ```
415///
416/// # Example: RFC 3339 compatible output with fractional seconds
417///
418/// ```
419/// use jiff::{civil::date, fmt::strtime};
420///
421/// let zdt = date(2024, 7, 15)
422/// .at(16, 24, 59, 123_456_789)
423/// .in_tz("America/New_York")?;
424/// let string = strtime::format("%Y-%m-%dT%H:%M:%S%.f%:z", &zdt)?;
425/// assert_eq!(string, "2024-07-15T16:24:59.123456789-04:00");
426///
427/// # Ok::<(), Box<dyn std::error::Error>>(())
428/// ```
429#[cfg(any(test, feature = "alloc"))]
430#[inline]
431pub fn format(
432 format: impl AsRef<[u8]>,
433 broken_down_time: impl Into<BrokenDownTime>,
434) -> Result<alloc::string::String, Error> {
435 let broken_down_time: BrokenDownTime = broken_down_time.into();
436
437 let format = format.as_ref();
438 let mut buf = alloc::string::String::with_capacity(format.len());
439 broken_down_time.format(format, &mut buf)?;
440 Ok(buf)
441}
442
443/// Configuration for customizing the behavior of formatting or parsing.
444///
445/// One important use case enabled by this type is the ability to set a
446/// [`Custom`] trait implementation to use when calling
447/// [`BrokenDownTime::format_with_config`]
448/// or [`BrokenDownTime::to_string_with_config`].
449///
450/// It is generally expected that most callers should not need to use this.
451/// At present, the only reasons to use this are:
452///
453/// * If you specifically need to provide locale aware formatting within
454/// the context of `strtime`-style APIs. Unless you specifically need this,
455/// you should prefer using the [`icu`] crate via [`jiff-icu`] to do type
456/// conversions. More specifically, follow the examples in the `icu::datetime`
457/// module for a modern approach to datetime localization that leverages
458/// Unicode.
459/// * If you specifically need to opt into "lenient" parsing such that most
460/// errors when formatting are silently ignored.
461///
462/// # Example
463///
464/// This example shows how to use [`PosixCustom`] via `strtime` formatting:
465///
466/// ```
467/// use jiff::{civil, fmt::strtime::{BrokenDownTime, PosixCustom, Config}};
468///
469/// let config = Config::new().custom(PosixCustom::new());
470/// let dt = civil::date(2025, 7, 1).at(17, 30, 0, 0);
471/// let tm = BrokenDownTime::from(dt);
472/// assert_eq!(
473/// tm.to_string_with_config(&config, "%c")?,
474/// "Tue Jul 1 17:30:00 2025",
475/// );
476///
477/// # Ok::<(), Box<dyn std::error::Error>>(())
478/// ```
479///
480/// [`icu`]: https://docs.rs/icu
481/// [`jiff-icu`]: https://docs.rs/jiff-icu
482#[derive(Clone, Debug)]
483pub struct Config<C: ?Sized> {
484 lenient: bool,
485 // This must remain the final field so that `Config<C>` can be unsized to
486 // `Config<dyn Custom>`.
487 custom: C,
488}
489
490impl Config<DefaultCustom> {
491 /// Create a new default `Config` that uses [`DefaultCustom`].
492 #[inline]
493 pub const fn new() -> Config<DefaultCustom> {
494 Config { lenient: false, custom: DefaultCustom::new() }
495 }
496}
497
498impl<C> Config<C> {
499 /// Set the implementation of [`Custom`] to use in `strtime`-style APIs
500 /// that use this configuration.
501 #[inline]
502 pub fn custom<U: Custom>(self, custom: U) -> Config<U> {
503 Config { lenient: self.lenient, custom }
504 }
505
506 /// Enable lenient formatting.
507 ///
508 /// When this is enabled, most errors that occur during formatting are
509 /// silently ignored. For example, if you try to format `%z` with a
510 /// [`BrokenDownTime`] that lacks a time zone offset, this would normally
511 /// result in an error. In contrast, when lenient mode is enabled, this
512 /// would just result in `%z` being written literally. Similarly, using
513 /// invalid UTF-8 in the format string would normally result in an error.
514 /// In lenient mode, invalid UTF-8 is automatically turned into the Unicode
515 /// replacement codepoint `U+FFFD` (which looks like this: `�`).
516 ///
517 /// Generally speaking, when this is enabled, the only error that can
518 /// occur when formatting is if a write to the underlying writer fails.
519 /// When using a writer that never errors (like `String`, unless allocation
520 /// fails), it follows that enabling lenient parsing will result in a
521 /// formatting operation that never fails (unless allocation fails).
522 ///
523 /// This currently has no effect on parsing, although this may change in
524 /// the future.
525 ///
526 /// Lenient formatting is disabled by default. It is strongly recommended
527 /// to keep it disabled in order to avoid mysterious failure modes for end
528 /// users. You should only enable this if you have strict requirements to
529 /// conform to legacy software behavior.
530 ///
531 /// # API stability
532 ///
533 /// An artifact of lenient parsing is that most error behaviors are
534 /// squashed in favor of writing the errant conversion specifier literally.
535 /// This means that if you use something like `%+`, which is currently
536 /// unrecognized, then that will result in a literal `%+` in the string
537 /// returned. But Jiff may one day add support for `%+` in a semver
538 /// compatible release.
539 ///
540 /// Stated differently, the set of unknown or error conditions is not
541 /// fixed and may decrease with time. This in turn means that the precise
542 /// conditions under which a conversion specifier gets written literally
543 /// to the resulting string may change over time in semver compatible
544 /// releases of Jiff.
545 ///
546 /// The alternative would be that Jiff could never add any new conversion
547 /// specifiers without making a semver incompatible release. The intent
548 /// of this policy is to avoid that scenario and permit reasonable
549 /// evolution of Jiff's `strtime` support.
550 ///
551 /// # Example
552 ///
553 /// This example shows how `%z` will be written literally if it would
554 /// otherwise fail:
555 ///
556 /// ```
557 /// use jiff::{civil, fmt::strtime::{BrokenDownTime, Config}};
558 ///
559 /// let tm = BrokenDownTime::from(civil::date(2025, 4, 30));
560 /// assert_eq!(
561 /// tm.to_string("%F %z").unwrap_err().to_string(),
562 /// "strftime formatting failed: %z failed: \
563 /// requires time zone offset",
564 /// );
565 ///
566 /// // Now enable lenient mode:
567 /// let config = Config::new().lenient(true);
568 /// assert_eq!(
569 /// tm.to_string_with_config(&config, "%F %z").unwrap(),
570 /// "2025-04-30 %z",
571 /// );
572 ///
573 /// // Lenient mode also applies when using an unsupported
574 /// // or unrecognized conversion specifier. This would
575 /// // normally return an error for example:
576 /// assert_eq!(
577 /// tm.to_string_with_config(&config, "%+ %0").unwrap(),
578 /// "%+ %0",
579 /// );
580 /// ```
581 #[inline]
582 pub fn lenient(self, yes: bool) -> Config<C> {
583 Config { lenient: yes, ..self }
584 }
585}
586
587/// An interface for customizing `strtime`-style parsing and formatting.
588///
589/// Each method on this trait comes with a default implementation corresponding
590/// to the behavior of [`DefaultCustom`]. More methods on this trait may be
591/// added in the future.
592///
593/// Implementers of this trait can be attached to a [`Config`] which can then
594/// be passed to [`BrokenDownTime::format_with_config`] or
595/// [`BrokenDownTime::to_string_with_config`].
596///
597/// New methods with default implementations may be added to this trait in
598/// semver compatible releases of Jiff.
599///
600/// # Motivation
601///
602/// While Jiff's API is generally locale-agnostic, this trait is meant to
603/// provide a best effort "hook" for tailoring the behavior of `strtime`
604/// routines. More specifically, for conversion specifiers in `strtime`-style
605/// APIs that are influenced by locale settings.
606///
607/// In general, a `strtime`-style API is not optimal for localization.
608/// It's both too flexible and not expressive enough. As a result, mixing
609/// localization with `strtime`-style APIs is likely not a good idea. However,
610/// this is sometimes required for legacy or convenience reasons, and that's
611/// why Jiff provides this hook.
612///
613/// If you do need to localize datetimes but don't have a requirement to
614/// have it integrate with `strtime`-style APIs, then you should use the
615/// [`icu`] crate via [`jiff-icu`] for type conversions. And then follow the
616/// examples in the `icu::datetime` API for formatting datetimes.
617///
618/// # Supported conversion specifiers
619///
620/// Currently, only formatting for the following specifiers is supported:
621///
622/// * `%c` - Formatting the date and time.
623/// * `%r` - Formatting the 12-hour clock time.
624/// * `%X` - Formatting the clock time.
625/// * `%x` - Formatting the date.
626///
627/// # Unsupported behavior
628///
629/// This trait currently does not support parsing based on locale in any way.
630///
631/// This trait also does not support locale specific behavior for `%a`/`%A`
632/// (day of the week), `%b`/`%B` (name of the month) or `%p`/`%P` (AM or PM).
633/// Supporting these is problematic with modern localization APIs, since
634/// modern APIs do not expose options to localize these things independent of
635/// anything else. Instead, they are subsumed most holistically into, e.g.,
636/// "print the long form of a date in the current locale."
637///
638/// Since the motivation for this trait is not really to provide the best way
639/// to localize datetimes, but rather, to facilitate convenience and
640/// inter-operation with legacy systems, it is plausible that the behaviors
641/// listed above could be supported by Jiff. If you need the above behaviors,
642/// please [open a new issue](https://github.com/BurntSushi/jiff/issues/new)
643/// with a proposal.
644///
645/// # Example
646///
647/// This example shows the difference between the default locale and the
648/// POSIX locale:
649///
650/// ```
651/// use jiff::{civil, fmt::strtime::{BrokenDownTime, PosixCustom, Config}};
652///
653/// let dt = civil::date(2025, 7, 1).at(17, 30, 0, 0);
654/// let tm = BrokenDownTime::from(dt);
655/// assert_eq!(
656/// tm.to_string("%c")?,
657/// "2025 M07 1, Tue 17:30:00",
658/// );
659///
660/// let config = Config::new().custom(PosixCustom::new());
661/// assert_eq!(
662/// tm.to_string_with_config(&config, "%c")?,
663/// "Tue Jul 1 17:30:00 2025",
664/// );
665///
666/// # Ok::<(), Box<dyn std::error::Error>>(())
667/// ```
668///
669/// # Trait objects
670///
671/// `Custom` is dyn-compatible. A configuration containing a concrete
672/// implementation can be coerced to one containing a `dyn Custom` trait
673/// object without allocating:
674///
675/// ```
676/// use jiff::{civil, fmt::strtime::{BrokenDownTime, PosixCustom, Config, Custom}};
677///
678/// let config = Config::new().custom(PosixCustom::new());
679/// let config: &Config<dyn Custom> = &config;
680/// let tm = BrokenDownTime::from(civil::date(2025, 7, 1).at(17, 30, 0, 0));
681/// assert_eq!(
682/// tm.to_string_with_config(config, "%c")?,
683/// "Tue Jul 1 17:30:00 2025",
684/// );
685///
686/// # Ok::<(), Box<dyn std::error::Error>>(())
687/// ```
688///
689/// [`icu`]: https://docs.rs/icu
690/// [`jiff-icu`]: https://docs.rs/jiff-icu
691pub trait Custom {
692 /// Called when formatting a datetime with the `%c` flag.
693 ///
694 /// This defaults to the implementation for [`DefaultCustom`].
695 fn format_datetime(
696 &self,
697 config: &Config<dyn Custom + '_>,
698 ext: &Extension,
699 tm: &BrokenDownTime,
700 wtr: &mut dyn Write,
701 ) -> Result<(), Error> {
702 if matches!(ext.flag, Some(Flag::Uppercase)) {
703 tm.format_with_config(config, "%Y M%m %-d, %^a %H:%M:%S", wtr)
704 } else {
705 tm.format_with_config(config, "%Y M%m %-d, %a %H:%M:%S", wtr)
706 }
707 }
708
709 /// Called when formatting a datetime with the `%x` flag.
710 ///
711 /// This defaults to the implementation for [`DefaultCustom`].
712 fn format_date(
713 &self,
714 config: &Config<dyn Custom + '_>,
715 _ext: &Extension,
716 tm: &BrokenDownTime,
717 wtr: &mut dyn Write,
718 ) -> Result<(), Error> {
719 // 2025 M04 27
720 tm.format_with_config(config, "%Y M%m %-d", wtr)
721 }
722
723 /// Called when formatting a datetime with the `%X` flag.
724 ///
725 /// This defaults to the implementation for [`DefaultCustom`].
726 fn format_time(
727 &self,
728 config: &Config<dyn Custom + '_>,
729 _ext: &Extension,
730 tm: &BrokenDownTime,
731 wtr: &mut dyn Write,
732 ) -> Result<(), Error> {
733 tm.format_with_config(config, "%H:%M:%S", wtr)
734 }
735
736 /// Called when formatting a datetime with the `%r` flag.
737 ///
738 /// This defaults to the implementation for [`DefaultCustom`].
739 fn format_12hour_time(
740 &self,
741 config: &Config<dyn Custom + '_>,
742 ext: &Extension,
743 tm: &BrokenDownTime,
744 wtr: &mut dyn Write,
745 ) -> Result<(), Error> {
746 if matches!(ext.flag, Some(Flag::Uppercase)) {
747 tm.format_with_config(config, "%-I:%M:%S %^p", wtr)
748 } else {
749 tm.format_with_config(config, "%-I:%M:%S %p", wtr)
750 }
751 }
752}
753
754/// The default trait implementation of [`Custom`].
755///
756/// Whenever one uses the formatting or parsing routines in this module
757/// without providing a configuration, then this customization is the one
758/// that gets used.
759///
760/// The behavior of the locale formatting of this type is meant to match that
761/// of Unicode's `und` locale.
762///
763/// # Example
764///
765/// This example shows how to explicitly use [`DefaultCustom`] via `strtime`
766/// formatting:
767///
768/// ```
769/// use jiff::{civil, fmt::strtime::{BrokenDownTime, DefaultCustom, Config}};
770///
771/// let config = Config::new().custom(DefaultCustom::new());
772/// let dt = civil::date(2025, 7, 1).at(17, 30, 0, 0);
773/// let tm = BrokenDownTime::from(dt);
774/// assert_eq!(
775/// tm.to_string_with_config(&config, "%c")?,
776/// "2025 M07 1, Tue 17:30:00",
777/// );
778///
779/// # Ok::<(), Box<dyn std::error::Error>>(())
780/// ```
781#[derive(Clone, Debug, Default)]
782pub struct DefaultCustom(());
783
784impl DefaultCustom {
785 /// Create a new instance of this default customization.
786 pub const fn new() -> DefaultCustom {
787 DefaultCustom(())
788 }
789}
790
791impl Custom for DefaultCustom {}
792
793/// A POSIX locale implementation of [`Custom`].
794///
795/// The behavior of the locale formatting of this type is meant to match that
796/// of POSIX's `C` locale.
797///
798/// # Example
799///
800/// This example shows how to use [`PosixCustom`] via `strtime` formatting:
801///
802/// ```
803/// use jiff::{civil, fmt::strtime::{BrokenDownTime, PosixCustom, Config}};
804///
805/// let config = Config::new().custom(PosixCustom::new());
806/// let dt = civil::date(2025, 7, 1).at(17, 30, 0, 0);
807/// let tm = BrokenDownTime::from(dt);
808/// assert_eq!(
809/// tm.to_string_with_config(&config, "%c")?,
810/// "Tue Jul 1 17:30:00 2025",
811/// );
812///
813/// # Ok::<(), Box<dyn std::error::Error>>(())
814/// ```
815#[derive(Clone, Debug, Default)]
816pub struct PosixCustom(());
817
818impl PosixCustom {
819 /// Create a new instance of this POSIX customization.
820 pub const fn new() -> PosixCustom {
821 PosixCustom(())
822 }
823}
824
825impl Custom for PosixCustom {
826 fn format_datetime(
827 &self,
828 config: &Config<dyn Custom + '_>,
829 ext: &Extension,
830 tm: &BrokenDownTime,
831 wtr: &mut dyn Write,
832 ) -> Result<(), Error> {
833 if matches!(ext.flag, Some(Flag::Uppercase)) {
834 tm.format_with_config(config, "%^a %^b %e %H:%M:%S %Y", wtr)
835 } else {
836 tm.format_with_config(config, "%a %b %e %H:%M:%S %Y", wtr)
837 }
838 }
839
840 fn format_date(
841 &self,
842 config: &Config<dyn Custom + '_>,
843 _ext: &Extension,
844 tm: &BrokenDownTime,
845 wtr: &mut dyn Write,
846 ) -> Result<(), Error> {
847 tm.format_with_config(config, "%m/%d/%y", wtr)
848 }
849
850 fn format_time(
851 &self,
852 config: &Config<dyn Custom + '_>,
853 _ext: &Extension,
854 tm: &BrokenDownTime,
855 wtr: &mut dyn Write,
856 ) -> Result<(), Error> {
857 tm.format_with_config(config, "%H:%M:%S", wtr)
858 }
859
860 fn format_12hour_time(
861 &self,
862 config: &Config<dyn Custom + '_>,
863 ext: &Extension,
864 tm: &BrokenDownTime,
865 wtr: &mut dyn Write,
866 ) -> Result<(), Error> {
867 if matches!(ext.flag, Some(Flag::Uppercase)) {
868 tm.format_with_config(config, "%I:%M:%S %^p", wtr)
869 } else {
870 tm.format_with_config(config, "%I:%M:%S %p", wtr)
871 }
872 }
873}
874
875/// The "broken down time" used by parsing and formatting.
876///
877/// This is a lower level aspect of the `strptime` and `strftime` APIs that you
878/// probably won't need to use directly. The main use case is if you want to
879/// observe formatting errors or if you want to format a datetime to something
880/// other than a `String` via the [`fmt::Write`](super::Write) trait.
881///
882/// Otherwise, typical use of this module happens indirectly via APIs like
883/// [`ZonedDateTime::strptime`] and [`ZonedDateTime::strftime`].
884///
885/// # Design
886///
887/// This is the type that parsing writes to and formatting reads from. That is,
888/// parsing proceeds by writing individual parsed fields to this type, and then
889/// converting the fields to datetime types like [`ZonedDateTime`] only after
890/// parsing is complete. Similarly, formatting always begins by converting
891/// datetime types like `ZonedDateTime` into a `BrokenDownTime`, and then
892/// formatting the individual fields from there.
893// Design:
894//
895// This is meant to be very similar to libc's `struct tm` in that it
896// represents civil time, although may have an offset attached to it, in which
897// case it represents an absolute time. The main difference is that each field
898// is explicitly optional, where as in C, there's no way to tell whether a
899// field is "set" or not. In C, this isn't so much a problem, because the
900// caller needs to explicitly pass in a pointer to a `struct tm`, and so the
901// API makes it clear that it's going to mutate the time.
902//
903// But in Rust, we really just want to accept a format string, an input and
904// return a fresh datetime. (Nevermind the fact that we don't provide a way
905// to mutate datetimes in place.) We could just use "default" units like you
906// might in C, but it would be very surprising if `%m-%d` just decided to fill
907// in the year for you with some default value. So we track which pieces have
908// been set individually and return errors when requesting, e.g., a `Date`
909// when no `year` has been parsed.
910//
911// We do permit time units to be filled in by default, as-is consistent with
912// the rest of Jiff's API. e.g., If a `DateTime` is requested but the format
913// string has no directives for time, we'll happy default to midnight. The
914// only catch is that you can't omit time units bigger than any present time
915// unit. For example, only `%M` doesn't fly. If you want to parse minutes, you
916// also have to parse hours.
917#[derive(Debug, Default)]
918#[cfg_attr(feature = "defmt", derive(defmt::Format))]
919pub struct BrokenDownTime {
920 year: Option<i16>,
921 month: Option<i8>,
922 day: Option<i8>,
923 day_of_year: Option<i16>,
924 iso_week_year: Option<i16>,
925 iso_week: Option<i8>,
926 week_sun: Option<i8>,
927 week_mon: Option<i8>,
928 hour: Option<i8>,
929 minute: Option<i8>,
930 second: Option<i8>,
931 subsec: Option<i32>,
932 offset: Option<Offset>,
933 // Used to confirm that it is consistent
934 // with the date given. It usually isn't
935 // used to pick a date on its own, but can
936 // be for week dates.
937 weekday: Option<Weekday>,
938 // Only generally useful with %I. But can still
939 // be used with, say, %H. In that case, AM will
940 // turn 13 o'clock to 1 o'clock.
941 meridiem: Option<Meridiem>,
942 // A timestamp. Set when converting from
943 // a `ZonedDateTime` or `Timestamp`, or when parsing `%s`.
944 timestamp: Option<Timestamp>,
945 // The time zone. Currently used only when
946 // formatting a `ZonedDateTime` or `Timestamp`.
947 tz: Option<TimeZone>,
948 // The IANA time zone identifier. Set when
949 // parsing `%Q` or by the caller.
950 #[cfg(feature = "alloc")]
951 #[cfg_attr(feature = "defmt", defmt(Debug2Format))]
952 iana: Option<alloc::string::String>,
953 // When true and `iana` is `None`, the IANA
954 // identifier is borrowed from `tz`. This avoids
955 // an allocation on every `ZonedDateTime::strftime`.
956 #[cfg(feature = "alloc")]
957 iana_from_tz: bool,
958}
959
960impl BrokenDownTime {
961 /// Parse the given `input` according to the given `format` string.
962 ///
963 /// See the [module documentation](self) for details on what's supported.
964 ///
965 /// This routine is the same as the module level free function
966 /// [`strtime::parse`](parse()).
967 ///
968 /// # Errors
969 ///
970 /// This returns an error when parsing failed. This might happen because
971 /// the format string itself was invalid, or because the input didn't match
972 /// the format string.
973 ///
974 /// # Example
975 ///
976 /// ```
977 /// use jiff::{civil, fmt::strtime::BrokenDownTime};
978 ///
979 /// let tm = BrokenDownTime::parse("%m/%d/%y", "7/14/24")?;
980 /// let date = tm.to_date()?;
981 /// assert_eq!(date, civil::date(2024, 7, 14));
982 ///
983 /// # Ok::<(), Box<dyn std::error::Error>>(())
984 /// ```
985 #[inline]
986 pub fn parse(
987 format: impl AsRef<[u8]>,
988 input: impl AsRef<[u8]>,
989 ) -> Result<BrokenDownTime, Error> {
990 BrokenDownTime::parse_mono(format.as_ref(), input.as_ref())
991 }
992
993 #[inline]
994 fn parse_mono(fmt: &[u8], inp: &[u8]) -> Result<BrokenDownTime, Error> {
995 let mut pieces = BrokenDownTime::default();
996 let mut p = Parser { fmt, inp, tm: &mut pieces };
997 p.parse().context(E::FailedStrptime)?;
998 if !p.inp.is_empty() {
999 return Err(Error::from(E::unconsumed(p.inp)));
1000 }
1001 Ok(pieces)
1002 }
1003
1004 /// Parse a prefix of the given `input` according to the given `format`
1005 /// string. The offset returned corresponds to the number of bytes parsed.
1006 /// That is, the length of the prefix (which may be the length of the
1007 /// entire input if there are no unparsed bytes remaining).
1008 ///
1009 /// See the [module documentation](self) for details on what's supported.
1010 ///
1011 /// This is like [`BrokenDownTime::parse`], but it won't return an error
1012 /// if there is input remaining after parsing the format directives.
1013 ///
1014 /// # Errors
1015 ///
1016 /// This returns an error when parsing failed. This might happen because
1017 /// the format string itself was invalid, or because the input didn't match
1018 /// the format string.
1019 ///
1020 /// # Example
1021 ///
1022 /// ```
1023 /// use jiff::{civil, fmt::strtime::BrokenDownTime};
1024 ///
1025 /// // %y only parses two-digit years, so the 99 following
1026 /// // 24 is unparsed!
1027 /// let input = "7/14/2499";
1028 /// let (tm, offset) = BrokenDownTime::parse_prefix("%m/%d/%y", input)?;
1029 /// let date = tm.to_date()?;
1030 /// assert_eq!(date, civil::date(2024, 7, 14));
1031 /// assert_eq!(offset, 7);
1032 /// assert_eq!(&input[offset..], "99");
1033 ///
1034 /// # Ok::<(), Box<dyn std::error::Error>>(())
1035 /// ```
1036 ///
1037 /// If the entire input is parsed, then the offset is the length of the
1038 /// input:
1039 ///
1040 /// ```
1041 /// use jiff::{civil, fmt::strtime::BrokenDownTime};
1042 ///
1043 /// let (tm, offset) = BrokenDownTime::parse_prefix(
1044 /// "%m/%d/%y", "7/14/24",
1045 /// )?;
1046 /// let date = tm.to_date()?;
1047 /// assert_eq!(date, civil::date(2024, 7, 14));
1048 /// assert_eq!(offset, 7);
1049 ///
1050 /// # Ok::<(), Box<dyn std::error::Error>>(())
1051 /// ```
1052 ///
1053 /// # Example: how to parse only a part of a timestamp
1054 ///
1055 /// If you only need, for example, the date from a timestamp, then you
1056 /// can parse it as a prefix:
1057 ///
1058 /// ```
1059 /// use jiff::{civil, fmt::strtime::BrokenDownTime};
1060 ///
1061 /// let input = "2024-01-20T17:55Z";
1062 /// let (tm, offset) = BrokenDownTime::parse_prefix("%Y-%m-%d", input)?;
1063 /// let date = tm.to_date()?;
1064 /// assert_eq!(date, civil::date(2024, 1, 20));
1065 /// assert_eq!(offset, 10);
1066 /// assert_eq!(&input[offset..], "T17:55Z");
1067 ///
1068 /// # Ok::<(), Box<dyn std::error::Error>>(())
1069 /// ```
1070 ///
1071 /// Note though that Jiff's default parsing functions are already quite
1072 /// flexible, and one can just parse a civil date directly from a timestamp
1073 /// automatically:
1074 ///
1075 /// ```
1076 /// use jiff::civil;
1077 ///
1078 /// let input = "2024-01-20T17:55-05";
1079 /// let date: civil::Date = input.parse()?;
1080 /// assert_eq!(date, civil::date(2024, 1, 20));
1081 ///
1082 /// # Ok::<(), Box<dyn std::error::Error>>(())
1083 /// ```
1084 ///
1085 /// Although in this case, you don't get the length of the prefix parsed.
1086 #[inline]
1087 pub fn parse_prefix(
1088 format: impl AsRef<[u8]>,
1089 input: impl AsRef<[u8]>,
1090 ) -> Result<(BrokenDownTime, usize), Error> {
1091 BrokenDownTime::parse_prefix_mono(format.as_ref(), input.as_ref())
1092 }
1093
1094 #[inline]
1095 fn parse_prefix_mono(
1096 fmt: &[u8],
1097 inp: &[u8],
1098 ) -> Result<(BrokenDownTime, usize), Error> {
1099 let mkoffset = util::parse::offseter(inp);
1100 let mut pieces = BrokenDownTime::default();
1101 let mut p = Parser { fmt, inp, tm: &mut pieces };
1102 p.parse().context(E::FailedStrptime)?;
1103 let remainder = mkoffset(p.inp);
1104 Ok((pieces, remainder))
1105 }
1106
1107 /// Format this broken down time using the format string given.
1108 ///
1109 /// See the [module documentation](self) for details on what's supported.
1110 ///
1111 /// This routine is like the module level free function
1112 /// [`strtime::format`](parse()), except it takes a
1113 /// [`fmt::Write`](super::Write) trait implementations instead of assuming
1114 /// you want a `String`.
1115 ///
1116 /// # Errors
1117 ///
1118 /// This returns an error when formatting failed. Formatting can fail
1119 /// either because of an invalid format string, or if formatting requires
1120 /// a field in `BrokenDownTime` to be set that isn't. For example, trying
1121 /// to format a [`DateTime`] with the `%z` specifier will fail because a
1122 /// `DateTime` has no time zone or offset information associated with it.
1123 ///
1124 /// Formatting also fails if writing to the given writer fails.
1125 ///
1126 /// # Example
1127 ///
1128 /// This example shows a formatting option, `%Z`, that isn't available
1129 /// during parsing. Namely, `%Z` inserts a time zone abbreviation. This
1130 /// is generally only intended for display purposes, since it can be
1131 /// ambiguous when parsing.
1132 ///
1133 /// ```
1134 /// use jiff::{civil::date, fmt::strtime::BrokenDownTime};
1135 ///
1136 /// let zdt = date(2024, 7, 9).at(16, 24, 0, 0).in_tz("America/New_York")?;
1137 /// let tm = BrokenDownTime::from(&zdt);
1138 ///
1139 /// let mut buf = String::new();
1140 /// tm.format("%a %b %e %I:%M:%S %p %Z %Y", &mut buf)?;
1141 ///
1142 /// assert_eq!(buf, "Tue Jul 9 04:24:00 PM EDT 2024");
1143 ///
1144 /// # Ok::<(), Box<dyn std::error::Error>>(())
1145 /// ```
1146 #[inline]
1147 pub fn format<W: Write>(
1148 &self,
1149 format: impl AsRef<[u8]>,
1150 mut wtr: W,
1151 ) -> Result<(), Error> {
1152 self.format_with_config(&Config::new(), format, &mut wtr)
1153 }
1154
1155 /// Format this broken down time with a specific configuration using the
1156 /// format string given.
1157 ///
1158 /// See the [module documentation](self) for details on what's supported.
1159 ///
1160 /// This routine is like [`BrokenDownTime::format`], except that it
1161 /// permits callers to provide their own configuration instead of using
1162 /// the default. This routine also accepts a `&mut dyn Write` instead of a
1163 /// `W`, which may be more flexible in some situations.
1164 ///
1165 /// # Errors
1166 ///
1167 /// This returns an error when formatting failed. Formatting can fail
1168 /// either because of an invalid format string, or if formatting requires
1169 /// a field in `BrokenDownTime` to be set that isn't. For example, trying
1170 /// to format a [`DateTime`] with the `%z` specifier will fail because a
1171 /// `DateTime` has no time zone or offset information associated with it.
1172 ///
1173 /// Formatting also fails if writing to the given writer fails.
1174 ///
1175 /// # Example
1176 ///
1177 /// This example shows how to use [`PosixCustom`] to get formatting
1178 /// for conversion specifiers like `%c` in the POSIX locale:
1179 ///
1180 /// ```
1181 /// use jiff::{civil, fmt::strtime::{BrokenDownTime, PosixCustom, Config}};
1182 ///
1183 /// let mut buf = String::new();
1184 /// let dt = civil::date(2025, 7, 1).at(17, 30, 0, 0);
1185 /// let tm = BrokenDownTime::from(dt);
1186 /// tm.format("%c", &mut buf)?;
1187 /// assert_eq!(buf, "2025 M07 1, Tue 17:30:00");
1188 ///
1189 /// let config = Config::new().custom(PosixCustom::new());
1190 /// buf.clear();
1191 /// tm.format_with_config(&config, "%c", &mut buf)?;
1192 /// assert_eq!(buf, "Tue Jul 1 17:30:00 2025");
1193 ///
1194 /// # Ok::<(), Box<dyn std::error::Error>>(())
1195 /// ```
1196 #[inline(never)]
1197 pub fn format_with_config(
1198 &self,
1199 config: &Config<dyn Custom + '_>,
1200 format: impl AsRef<[u8]>,
1201 wtr: &mut dyn Write,
1202 ) -> Result<(), Error> {
1203 let fmt = format.as_ref();
1204 let mut buf = ArrayBuffer::<100>::default();
1205 let mut bbuf = buf.as_borrowed();
1206 let mut wtr = BorrowedWriter::new(&mut bbuf, wtr);
1207 let mut formatter = Formatter { config, fmt, tm: self, wtr: &mut wtr };
1208 formatter.format().context(E::FailedStrftime)?;
1209 wtr.finish()
1210 }
1211
1212 /// Format this broken down time using the format string given into a new
1213 /// `String`.
1214 ///
1215 /// See the [module documentation](self) for details on what's supported.
1216 ///
1217 /// This is like [`BrokenDownTime::format`], but always uses a `String` to
1218 /// format the time into. If you need to reuse allocations or write a
1219 /// formatted time into a different type, then you should use
1220 /// [`BrokenDownTime::format`] instead.
1221 ///
1222 /// # Errors
1223 ///
1224 /// This returns an error when formatting failed. Formatting can fail
1225 /// either because of an invalid format string, or if formatting requires
1226 /// a field in `BrokenDownTime` to be set that isn't. For example, trying
1227 /// to format a [`DateTime`] with the `%z` specifier will fail because a
1228 /// `DateTime` has no time zone or offset information associated with it.
1229 ///
1230 /// # Example
1231 ///
1232 /// This example shows a formatting option, `%Z`, that isn't available
1233 /// during parsing. Namely, `%Z` inserts a time zone abbreviation. This
1234 /// is generally only intended for display purposes, since it can be
1235 /// ambiguous when parsing.
1236 ///
1237 /// ```
1238 /// use jiff::{civil::date, fmt::strtime::BrokenDownTime};
1239 ///
1240 /// let zdt = date(2024, 7, 9).at(16, 24, 0, 0).in_tz("America/New_York")?;
1241 /// let tm = BrokenDownTime::from(&zdt);
1242 /// let string = tm.to_string("%a %b %e %I:%M:%S %p %Z %Y")?;
1243 /// assert_eq!(string, "Tue Jul 9 04:24:00 PM EDT 2024");
1244 ///
1245 /// # Ok::<(), Box<dyn std::error::Error>>(())
1246 /// ```
1247 #[cfg(feature = "alloc")]
1248 #[inline]
1249 pub fn to_string(
1250 &self,
1251 format: impl AsRef<[u8]>,
1252 ) -> Result<alloc::string::String, Error> {
1253 let format = format.as_ref();
1254 let mut buf = alloc::string::String::with_capacity(format.len());
1255 self.format(format, &mut buf)?;
1256 Ok(buf)
1257 }
1258
1259 /// Format this broken down time with a specific configuration using the
1260 /// format string given into a new `String`.
1261 ///
1262 /// See the [module documentation](self) for details on what's supported.
1263 ///
1264 /// This routine is like [`BrokenDownTime::to_string`], except that it
1265 /// permits callers to provide their own configuration instead of using
1266 /// the default.
1267 ///
1268 /// # Errors
1269 ///
1270 /// This returns an error when formatting failed. Formatting can fail
1271 /// either because of an invalid format string, or if formatting requires
1272 /// a field in `BrokenDownTime` to be set that isn't. For example, trying
1273 /// to format a [`DateTime`] with the `%z` specifier will fail because a
1274 /// `DateTime` has no time zone or offset information associated with it.
1275 ///
1276 /// # Example
1277 ///
1278 /// This example shows how to use [`PosixCustom`] to get formatting
1279 /// for conversion specifiers like `%c` in the POSIX locale:
1280 ///
1281 /// ```
1282 /// use jiff::{civil, fmt::strtime::{BrokenDownTime, PosixCustom, Config}};
1283 ///
1284 /// let dt = civil::date(2025, 7, 1).at(17, 30, 0, 0);
1285 /// let tm = BrokenDownTime::from(dt);
1286 /// assert_eq!(
1287 /// tm.to_string("%c")?,
1288 /// "2025 M07 1, Tue 17:30:00",
1289 /// );
1290 ///
1291 /// let config = Config::new().custom(PosixCustom::new());
1292 /// assert_eq!(
1293 /// tm.to_string_with_config(&config, "%c")?,
1294 /// "Tue Jul 1 17:30:00 2025",
1295 /// );
1296 ///
1297 /// # Ok::<(), Box<dyn std::error::Error>>(())
1298 /// ```
1299 #[cfg(feature = "alloc")]
1300 #[inline]
1301 pub fn to_string_with_config(
1302 &self,
1303 config: &Config<dyn Custom + '_>,
1304 format: impl AsRef<[u8]>,
1305 ) -> Result<alloc::string::String, Error> {
1306 let format = format.as_ref();
1307 let mut buf = alloc::string::String::with_capacity(format.len());
1308 self.format_with_config(config, format, &mut buf)?;
1309 Ok(buf)
1310 }
1311
1312 /// Extracts a zoned datetime from this broken down time.
1313 ///
1314 /// When an IANA time zone identifier is
1315 /// present but an offset is not, then the
1316 /// [`Disambiguation::Compatible`](crate::tz::Disambiguation::Compatible)
1317 /// strategy is used if the parsed datetime is ambiguous in the time zone.
1318 ///
1319 /// If you need to use a custom time zone database for doing IANA time
1320 /// zone identifier lookups (via the `%Q` directive), then use
1321 /// [`BrokenDownTime::to_zoned_datetime_with`].
1322 ///
1323 /// This always prefers an explicitly set timestamp over other components
1324 /// of this `BrokenDownTime`. An explicit timestamp is set via
1325 /// [`BrokenDownTime::set_timestamp`]. This most commonly occurs by parsing
1326 /// a `%s` conversion specifier. When an explicit timestamp is not present,
1327 /// then the instant is derived from a civil datetime with a UTC offset
1328 /// and/or a time zone.
1329 ///
1330 /// # Warning
1331 ///
1332 /// The `strtime` module APIs do not require an IANA time zone identifier
1333 /// to parse a `ZonedDateTime`. If one is not used, then if you format a
1334 /// zoned datetime in a time zone like `America/New_York` and then parse it
1335 /// back again, the zoned datetime you get back will be a "fixed offset"
1336 /// zoned datetime. This in turn means it will not perform daylight saving
1337 /// time safe arithmetic.
1338 ///
1339 /// However, the `%Q` directive may be used to both format and parse an
1340 /// IANA time zone identifier. It is strongly recommended to use this
1341 /// directive whenever one is formatting or parsing `ZonedDateTime` values
1342 /// since it permits correctly round-tripping `ZonedDateTime` values.
1343 ///
1344 /// # Errors
1345 ///
1346 /// This returns an error if there weren't enough components to construct
1347 /// an instant with a time zone. This requires an IANA time zone identifier
1348 /// or a UTC offset, as well as either an explicitly set timestamp (via
1349 /// [`BrokenDownTime::set_timestamp`]) or enough data set to form a civil
1350 /// datetime.
1351 ///
1352 /// When both a UTC offset and an IANA time zone identifier are found, then
1353 /// an error is returned if they are inconsistent with one another for the
1354 /// parsed timestamp.
1355 ///
1356 /// # Example
1357 ///
1358 /// This example shows how to parse a zoned datetime:
1359 ///
1360 /// ```
1361 /// use jiff::fmt::strtime;
1362 ///
1363 /// let zdt = strtime::parse(
1364 /// "%F %H:%M %:z %:Q",
1365 /// "2024-07-14 21:14 -04:00 America/New_York",
1366 /// )?.to_zoned_datetime()?;
1367 /// assert_eq!(
1368 /// zdt.to_string(),
1369 /// "2024-07-14T21:14:00-04:00[America/New_York]",
1370 /// );
1371 ///
1372 /// # Ok::<(), Box<dyn std::error::Error>>(())
1373 /// ```
1374 ///
1375 /// # Example: time zone inconsistent with offset
1376 ///
1377 /// This shows that an error is returned when the offset is inconsistent
1378 /// with the time zone. For example, `America/New_York` is in daylight
1379 /// saving time in July 2024:
1380 ///
1381 /// ```
1382 /// use jiff::fmt::strtime;
1383 ///
1384 /// let result = strtime::parse(
1385 /// "%F %H:%M %:z %:Q",
1386 /// "2024-07-14 21:14 -05:00 America/New_York",
1387 /// )?.to_zoned_datetime();
1388 /// assert_eq!(
1389 /// result.unwrap_err().to_string(),
1390 /// "datetime could not resolve to a timestamp since `reject` \
1391 /// conflict resolution was chosen, and because \
1392 /// datetime has offset `-05`, \
1393 /// but the time zone `America/New_York` for the given datetime \
1394 /// unambiguously has offset `-04`",
1395 /// );
1396 ///
1397 /// # Ok::<(), Box<dyn std::error::Error>>(())
1398 /// ```
1399 ///
1400 /// # Example: timestamp without offset
1401 ///
1402 /// If a timestamp has been parsed but there is no offset or IANA time
1403 /// zone identifier, then the zoned datetime will be in UTC via the
1404 /// `Etc/Unknown` time zone:
1405 ///
1406 /// ```
1407 /// use jiff::fmt::strtime;
1408 ///
1409 /// let zdt = strtime::parse("%s", "1760813400")?.to_zoned_datetime()?;
1410 /// assert_eq!(zdt.to_string(), "2025-10-18T18:50:00Z[Etc/Unknown]");
1411 ///
1412 /// # Ok::<(), Box<dyn std::error::Error>>(())
1413 /// ```
1414 #[inline]
1415 pub fn to_zoned_datetime(&self) -> Result<ZonedDateTime, Error> {
1416 self.to_zoned_datetime_with(crate::tz::db())
1417 }
1418
1419 /// Extracts a zoned datetime from this broken down time and uses the time
1420 /// zone database given for any IANA time zone identifier lookups.
1421 ///
1422 /// An IANA time zone identifier lookup is only performed when this
1423 /// `BrokenDownTime` contains an IANA time zone identifier. An IANA time
1424 /// zone identifier can be parsed with the `%Q` directive.
1425 ///
1426 /// When an IANA time zone identifier is
1427 /// present but an offset is not, then the
1428 /// [`Disambiguation::Compatible`](crate::tz::Disambiguation::Compatible)
1429 /// strategy is used if the parsed datetime is ambiguous in the time zone.
1430 ///
1431 /// This always prefers an explicitly set timestamp over other components
1432 /// of this `BrokenDownTime`. An explicit timestamp is set via
1433 /// [`BrokenDownTime::set_timestamp`]. This most commonly occurs by parsing
1434 /// a `%s` conversion specifier. When an explicit timestamp is not present,
1435 /// then the instant is derived from a civil datetime with a UTC offset
1436 /// and/or a time zone.
1437 ///
1438 /// # Warning
1439 ///
1440 /// The `strtime` module APIs do not require an IANA time zone identifier
1441 /// to parse a `ZonedDateTime`. If one is not used, then if you format a
1442 /// zoned datetime in a time zone like `America/New_York` and then parse it
1443 /// back again, the zoned datetime you get back will be a "fixed offset"
1444 /// zoned datetime. This in turn means it will not perform daylight saving
1445 /// time safe arithmetic.
1446 ///
1447 /// However, the `%Q` directive may be used to both format and parse an
1448 /// IANA time zone identifier. It is strongly recommended to use this
1449 /// directive whenever one is formatting or parsing `ZonedDateTime` values
1450 /// since it permits correctly round-tripping `ZonedDateTime` values.
1451 ///
1452 /// # Errors
1453 ///
1454 /// This returns an error if there weren't enough components to construct
1455 /// an instant with a time zone. This requires an IANA time zone identifier
1456 /// or a UTC offset, as well as either an explicitly set timestamp (via
1457 /// [`BrokenDownTime::set_timestamp`]) or enough data set to form a civil
1458 /// datetime.
1459 ///
1460 /// When both a UTC offset and an IANA time zone identifier are found, then
1461 /// an error is returned if they are inconsistent with one another for the
1462 /// parsed timestamp.
1463 ///
1464 /// # Example
1465 ///
1466 /// This example shows how to parse a zoned datetime:
1467 ///
1468 /// ```
1469 /// use jiff::fmt::strtime;
1470 ///
1471 /// let zdt = strtime::parse(
1472 /// "%F %H:%M %:z %:Q",
1473 /// "2024-07-14 21:14 -04:00 America/New_York",
1474 /// )?.to_zoned_datetime_with(jiff::tz::db())?;
1475 /// assert_eq!(
1476 /// zdt.to_string(),
1477 /// "2024-07-14T21:14:00-04:00[America/New_York]",
1478 /// );
1479 ///
1480 /// # Ok::<(), Box<dyn std::error::Error>>(())
1481 /// ```
1482 #[inline]
1483 pub fn to_zoned_datetime_with(
1484 &self,
1485 db: &TimeZoneDatabase,
1486 ) -> Result<ZonedDateTime, Error> {
1487 match (self.offset, self.iana_time_zone()) {
1488 (None, None) => {
1489 if let Some(ts) = self.timestamp {
1490 return Ok(ts.to_zoned_datetime(TimeZone::unknown()));
1491 }
1492 Err(Error::from(E::ZonedDateTimeOffsetOrTz))
1493 }
1494 (Some(offset), None) => {
1495 let ts = match self.timestamp {
1496 Some(ts) => ts,
1497 None => {
1498 let dt = self
1499 .to_datetime()
1500 .context(E::RequiredDateTimeForZonedDateTime)?;
1501 let ts = offset
1502 .to_timestamp(dt)
1503 .context(E::RangeTimestamp)?;
1504 ts
1505 }
1506 };
1507 Ok(ts.to_zoned_datetime(TimeZone::fixed(offset)))
1508 }
1509 (None, Some(iana)) => {
1510 let tz = db.get(iana)?;
1511 match self.timestamp {
1512 Some(ts) => Ok(ts.to_zoned_datetime(tz)),
1513 None => {
1514 let dt = self
1515 .to_datetime()
1516 .context(E::RequiredDateTimeForZonedDateTime)?;
1517 Ok(tz.to_zoned_datetime(dt)?)
1518 }
1519 }
1520 }
1521 (Some(offset), Some(iana)) => {
1522 let tz = db.get(iana)?;
1523 match self.timestamp {
1524 Some(ts) => {
1525 let zdt = ts.to_zoned_datetime(tz);
1526 if zdt.offset() != offset {
1527 return Err(Error::from(E::MismatchOffset {
1528 parsed: offset,
1529 got: zdt.offset(),
1530 }));
1531 }
1532 Ok(zdt)
1533 }
1534 None => {
1535 let dt = self
1536 .to_datetime()
1537 .context(E::RequiredDateTimeForZonedDateTime)?;
1538 let azdt =
1539 OffsetConflict::Reject.resolve(dt, offset, tz)?;
1540 // OffsetConflict::Reject guarantees no ambiguity, but
1541 // conversion can still fail if the timestamp is out
1542 // of range.
1543 azdt.unambiguous()
1544 }
1545 }
1546 }
1547 }
1548 }
1549
1550 /// Extracts a timestamp from this broken down time.
1551 ///
1552 /// This always prefers an explicitly set timestamp over other components
1553 /// of this `BrokenDownTime`. An explicit timestamp is set via
1554 /// [`BrokenDownTime::set_timestamp`]. This most commonly occurs by parsing
1555 /// a `%s` conversion specifier. When an explicit timestamp is not present,
1556 /// then the instant is derived from a civil datetime with a UTC offset.
1557 ///
1558 /// # Errors
1559 ///
1560 /// This returns an error if there weren't enough components to construct
1561 /// an instant. This requires either an explicitly set timestamp (via
1562 /// [`BrokenDownTime::set_timestamp`]) or enough data set to form a civil
1563 /// datetime _and_ a UTC offset.
1564 ///
1565 /// # Example
1566 ///
1567 /// This example shows how to parse a timestamp from a broken down time:
1568 ///
1569 /// ```
1570 /// use jiff::fmt::strtime;
1571 ///
1572 /// let ts = strtime::parse(
1573 /// "%F %H:%M %:z",
1574 /// "2024-07-14 21:14 -04:00",
1575 /// )?.to_timestamp()?;
1576 /// assert_eq!(ts.to_string(), "2024-07-15T01:14:00Z");
1577 ///
1578 /// # Ok::<(), Box<dyn std::error::Error>>(())
1579 /// ```
1580 ///
1581 /// # Example: conflicting data
1582 ///
1583 /// It is possible to parse both a timestamp and a civil datetime with an
1584 /// offset in the same string. This means there could be two potentially
1585 /// different ways to derive a timestamp from the parsed data. When that
1586 /// happens, any explicitly parsed timestamp (via `%s`) takes precedence
1587 /// for this method:
1588 ///
1589 /// ```
1590 /// use jiff::fmt::strtime;
1591 ///
1592 /// // The `%s` parse wins:
1593 /// let ts = strtime::parse(
1594 /// "%F %H:%M %:z and also %s",
1595 /// "2024-07-14 21:14 -04:00 and also 1760377242",
1596 /// )?.to_timestamp()?;
1597 /// assert_eq!(ts.to_string(), "2025-10-13T17:40:42Z");
1598 ///
1599 /// // Even when it is parsed first:
1600 /// let ts = strtime::parse(
1601 /// "%s and also %F %H:%M %:z",
1602 /// "1760377242 and also 2024-07-14 21:14 -04:00",
1603 /// )?.to_timestamp()?;
1604 /// assert_eq!(ts.to_string(), "2025-10-13T17:40:42Z");
1605 ///
1606 /// # Ok::<(), Box<dyn std::error::Error>>(())
1607 /// ```
1608 ///
1609 /// If you need access to the instant parsed by a civil datetime with an
1610 /// offset, then that is still available:
1611 ///
1612 /// ```
1613 /// use jiff::fmt::strtime;
1614 ///
1615 /// let tm = strtime::parse(
1616 /// "%F %H:%M %:z and also %s",
1617 /// "2024-07-14 21:14 -04:00 and also 1760377242",
1618 /// )?;
1619 /// assert_eq!(tm.to_timestamp()?.to_string(), "2025-10-13T17:40:42Z");
1620 ///
1621 /// let dt = tm.to_datetime()?;
1622 /// let offset = tm.offset().ok_or_else(|| "missing offset")?;
1623 /// let instant = offset.to_timestamp(dt)?;
1624 /// assert_eq!(instant.to_string(), "2024-07-15T01:14:00Z");
1625 ///
1626 /// # Ok::<(), Box<dyn std::error::Error>>(())
1627 /// ```
1628 #[inline]
1629 pub fn to_timestamp(&self) -> Result<Timestamp, Error> {
1630 // Previously, I had used this as the "fast path" and
1631 // put the conversion code below into a cold unlineable
1632 // function. But this "fast path" is actually the unusual
1633 // case. It's rare to parse a timestamp (as an integer
1634 // number of seconds since the Unix epoch) directly.
1635 // So the code below, while bigger, is the common case.
1636 // So it probably makes sense to keep it inlined.
1637 if let Some(timestamp) = self.timestamp() {
1638 return Ok(timestamp);
1639 }
1640 let dt =
1641 self.to_datetime().context(E::RequiredDateTimeForTimestamp)?;
1642 let offset = self.offset.ok_or(E::RequiredOffsetForTimestamp)?;
1643 offset.to_timestamp(dt).context(E::RangeTimestamp)
1644 }
1645
1646 /// Extracts a civil datetime from this broken down time.
1647 ///
1648 /// # Errors
1649 ///
1650 /// This returns an error if there weren't enough components to construct
1651 /// a civil datetime. This means there must be at least a year, month and
1652 /// day.
1653 ///
1654 /// It's okay if there are more units than are needed to construct a civil
1655 /// datetime. For example, if this broken down time contains an offset,
1656 /// then it won't prevent a conversion to a civil datetime.
1657 ///
1658 /// # Example
1659 ///
1660 /// This example shows how to parse a civil datetime from a broken down
1661 /// time:
1662 ///
1663 /// ```
1664 /// use jiff::fmt::strtime;
1665 ///
1666 /// let dt = strtime::parse("%F %H:%M", "2024-07-14 21:14")?.to_datetime()?;
1667 /// assert_eq!(dt.to_string(), "2024-07-14T21:14:00");
1668 ///
1669 /// # Ok::<(), Box<dyn std::error::Error>>(())
1670 /// ```
1671 #[inline]
1672 pub fn to_datetime(&self) -> Result<DateTime, Error> {
1673 let date = self.to_date().context(E::RequiredDateForDateTime)?;
1674 let time = self.to_time().context(E::RequiredTimeForDateTime)?;
1675 Ok(DateTime::from_parts(date, time))
1676 }
1677
1678 /// Extracts a civil date from this broken down time.
1679 ///
1680 /// This requires that the year (Gregorian or ISO 8601 week date year)
1681 /// is set along with a way to identify the day
1682 /// in the year. Typically identifying the day is done by setting the
1683 /// month and day, but this can also be done via a number of other means:
1684 ///
1685 /// * Via an ISO week date.
1686 /// * Via the day of the year.
1687 /// * Via a week date with Sunday as the start of the week.
1688 /// * Via a week date with Monday as the start of the week.
1689 ///
1690 /// # Errors
1691 ///
1692 /// This returns an error if there weren't enough components to construct
1693 /// a civil date, or if the components don't form into a valid date. This
1694 /// means there must be at least a year and a way to determine the day of
1695 /// the year.
1696 ///
1697 /// This will also return an error when there is a weekday component
1698 /// set to a value inconsistent with the date returned.
1699 ///
1700 /// It's okay if there are more units than are needed to construct a civil
1701 /// datetime. For example, if this broken down time contains a civil time,
1702 /// then it won't prevent a conversion to a civil date.
1703 ///
1704 /// # Example
1705 ///
1706 /// This example shows how to parse a civil date from a broken down time:
1707 ///
1708 /// ```
1709 /// use jiff::fmt::strtime;
1710 ///
1711 /// let date = strtime::parse("%m/%d/%y", "7/14/24")?.to_date()?;
1712 /// assert_eq!(date.to_string(), "2024-07-14");
1713 ///
1714 /// # Ok::<(), Box<dyn std::error::Error>>(())
1715 /// ```
1716 #[inline]
1717 pub fn to_date(&self) -> Result<Date, Error> {
1718 #[cold]
1719 #[inline(never)]
1720 fn to_date(tm: &BrokenDownTime) -> Result<Date, Error> {
1721 let Some(year) = tm.year else {
1722 // The Gregorian year and ISO week year may be parsed
1723 // separately. That is, they are two different fields. So if
1724 // the Gregorian year is absent, we might still have an ISO
1725 // 8601 week date.
1726 if let Some(date) = tm.to_date_from_iso()? {
1727 return Ok(date);
1728 }
1729 return Err(Error::from(E::RequiredYearForDate));
1730 };
1731 let mut date = tm.to_date_from_gregorian(year)?;
1732 if date.is_none() {
1733 date = tm.to_date_from_iso()?;
1734 }
1735 if date.is_none() {
1736 date = tm.to_date_from_day_of_year(year)?;
1737 }
1738 if date.is_none() {
1739 date = tm.to_date_from_week_sun(year)?;
1740 }
1741 if date.is_none() {
1742 date = tm.to_date_from_week_mon(year)?;
1743 }
1744 let Some(date) = date else {
1745 return Err(Error::from(E::RequiredSomeDayForDate));
1746 };
1747 if let Some(weekday) = tm.weekday {
1748 if weekday != date.weekday() {
1749 return Err(Error::from(E::MismatchWeekday {
1750 parsed: weekday,
1751 got: date.weekday(),
1752 }));
1753 }
1754 }
1755 Ok(date)
1756 }
1757
1758 // The common case is a simple Gregorian date.
1759 // We put the rest behind a non-inlineable function
1760 // to avoid code bloat for very uncommon cases.
1761 let (Some(year), Some(month), Some(day)) =
1762 (self.year, self.month, self.day)
1763 else {
1764 return to_date(self);
1765 };
1766 let date = Date::new(year, month, day).context(E::InvalidDate)?;
1767 if let Some(weekday) = self.weekday {
1768 if weekday != date.weekday() {
1769 return Err(Error::from(E::MismatchWeekday {
1770 parsed: weekday,
1771 got: date.weekday(),
1772 }));
1773 }
1774 }
1775 Ok(date)
1776 }
1777
1778 #[inline]
1779 fn to_date_from_gregorian(
1780 &self,
1781 year: i16,
1782 ) -> Result<Option<Date>, Error> {
1783 let (Some(month), Some(day)) = (self.month, self.day) else {
1784 return Ok(None);
1785 };
1786 Ok(Some(Date::new(year, month, day).context(E::InvalidDate)?))
1787 }
1788
1789 #[inline]
1790 fn to_date_from_day_of_year(
1791 &self,
1792 year: i16,
1793 ) -> Result<Option<Date>, Error> {
1794 let Some(doy) = self.day_of_year else { return Ok(None) };
1795 Ok(Some({
1796 let first = Date::new(year, 1, 1).unwrap();
1797 first.with().day_of_year(doy).build().context(E::InvalidDate)?
1798 }))
1799 }
1800
1801 #[inline]
1802 fn to_date_from_iso(&self) -> Result<Option<Date>, Error> {
1803 let (Some(y), Some(w), Some(d)) =
1804 (self.iso_week_year, self.iso_week, self.weekday)
1805 else {
1806 return Ok(None);
1807 };
1808 let wd = ISOWeekDate::new(y, w, d).context(E::InvalidISOWeekDate)?;
1809 Ok(Some(wd.date()))
1810 }
1811
1812 #[inline]
1813 fn to_date_from_week_sun(&self, year: i16) -> Result<Option<Date>, Error> {
1814 let (Some(week), Some(weekday)) = (self.week_sun, self.weekday) else {
1815 return Ok(None);
1816 };
1817 let week = i16::from(week);
1818 let wday = i16::from(weekday.to_sunday_zero_offset());
1819 let first_of_year = Date::new(year, 1, 1).context(E::InvalidDate)?;
1820 let first_sunday = first_of_year
1821 .nth_weekday_of_month(1, Weekday::Sunday)
1822 .map(|d| d.day_of_year())
1823 .context(E::InvalidDate)?;
1824 let doy = if week == 0 {
1825 let days_before_first_sunday = 7 - wday;
1826 let doy = first_sunday
1827 .checked_sub(days_before_first_sunday)
1828 .ok_or(E::InvalidWeekdaySunday { got: weekday })?;
1829 if doy == 0 {
1830 return Err(Error::from(E::InvalidWeekdaySunday {
1831 got: weekday,
1832 }));
1833 }
1834 doy
1835 } else {
1836 let days_since_first_sunday = (week - 1) * 7 + wday;
1837 let doy = first_sunday + days_since_first_sunday;
1838 doy
1839 };
1840 let date = first_of_year
1841 .with()
1842 .day_of_year(doy)
1843 .build()
1844 .context(E::InvalidDate)?;
1845 Ok(Some(date))
1846 }
1847
1848 #[inline]
1849 fn to_date_from_week_mon(&self, year: i16) -> Result<Option<Date>, Error> {
1850 let (Some(week), Some(weekday)) = (self.week_mon, self.weekday) else {
1851 return Ok(None);
1852 };
1853 let week = i16::from(week);
1854 let wday = i16::from(weekday.to_monday_zero_offset());
1855 let first_of_year = Date::new(year, 1, 1).context(E::InvalidDate)?;
1856 let first_monday = first_of_year
1857 .nth_weekday_of_month(1, Weekday::Monday)
1858 .map(|d| d.day_of_year())
1859 .context(E::InvalidDate)?;
1860 let doy = if week == 0 {
1861 let days_before_first_monday = 7 - wday;
1862 let doy = first_monday
1863 .checked_sub(days_before_first_monday)
1864 .ok_or(E::InvalidWeekdayMonday { got: weekday })?;
1865 if doy == 0 {
1866 return Err(Error::from(E::InvalidWeekdayMonday {
1867 got: weekday,
1868 }));
1869 }
1870 doy
1871 } else {
1872 let days_since_first_monday = (week - 1) * 7 + wday;
1873 let doy = first_monday + days_since_first_monday;
1874 doy
1875 };
1876 let date = first_of_year
1877 .with()
1878 .day_of_year(doy)
1879 .build()
1880 .context(E::InvalidDate)?;
1881 Ok(Some(date))
1882 }
1883
1884 /// Extracts a civil time from this broken down time.
1885 ///
1886 /// # Errors
1887 ///
1888 /// This returns an error if there weren't enough components to construct
1889 /// a civil time. Interestingly, this succeeds if there are no time units,
1890 /// since this will assume an absent time is midnight. However, this can
1891 /// still error when, for example, there are minutes but no hours.
1892 ///
1893 /// It's okay if there are more units than are needed to construct a civil
1894 /// time. For example, if this broken down time contains a date, then it
1895 /// won't prevent a conversion to a civil time.
1896 ///
1897 /// # Example
1898 ///
1899 /// This example shows how to parse a civil time from a broken down
1900 /// time:
1901 ///
1902 /// ```
1903 /// use jiff::fmt::strtime;
1904 ///
1905 /// let time = strtime::parse("%H:%M:%S", "21:14:59")?.to_time()?;
1906 /// assert_eq!(time.to_string(), "21:14:59");
1907 ///
1908 /// # Ok::<(), Box<dyn std::error::Error>>(())
1909 /// ```
1910 ///
1911 /// # Example: time defaults to midnight
1912 ///
1913 /// Since time defaults to midnight, one can parse an empty input string
1914 /// with an empty format string and still extract a `Time`:
1915 ///
1916 /// ```
1917 /// use jiff::fmt::strtime;
1918 ///
1919 /// let time = strtime::parse("", "")?.to_time()?;
1920 /// assert_eq!(time.to_string(), "00:00:00");
1921 ///
1922 /// # Ok::<(), Box<dyn std::error::Error>>(())
1923 /// ```
1924 ///
1925 /// # Example: invalid time
1926 ///
1927 /// Other than using illegal values (like `24` for hours), if lower units
1928 /// are parsed without higher units, then this results in an error:
1929 ///
1930 /// ```
1931 /// use jiff::fmt::strtime;
1932 ///
1933 /// assert!(strtime::parse("%M:%S", "15:36")?.to_time().is_err());
1934 ///
1935 /// # Ok::<(), Box<dyn std::error::Error>>(())
1936 /// ```
1937 ///
1938 /// # Example: invalid date
1939 ///
1940 /// Since validation of a date is only done when a date is requested, it is
1941 /// actually possible to parse an invalid date and extract the time without
1942 /// an error occurring:
1943 ///
1944 /// ```
1945 /// use jiff::fmt::strtime;
1946 ///
1947 /// // 31 is a legal day value, but not for June. However, this is
1948 /// // not validated unless you ask for a `Date` from the parsed
1949 /// // `BrokenDownTime`. Most other higher level accessors on this
1950 /// // type need to create a date, but this routine does not. So
1951 /// // asking for only a `time` will circumvent date validation!
1952 /// let tm = strtime::parse("%Y-%m-%d %H:%M:%S", "2024-06-31 21:14:59")?;
1953 /// let time = tm.to_time()?;
1954 /// assert_eq!(time.to_string(), "21:14:59");
1955 ///
1956 /// # Ok::<(), Box<dyn std::error::Error>>(())
1957 /// ```
1958 #[inline]
1959 pub fn to_time(&self) -> Result<Time, Error> {
1960 let Some(hour) = self.hour() else {
1961 if self.minute.is_some() {
1962 return Err(Error::from(E::MissingTimeHourForMinute));
1963 }
1964 if self.second.is_some() {
1965 return Err(Error::from(E::MissingTimeHourForSecond));
1966 }
1967 if self.subsec.is_some() {
1968 return Err(Error::from(E::MissingTimeHourForFractional));
1969 }
1970 return Ok(Time::midnight());
1971 };
1972 let Some(minute) = self.minute() else {
1973 if self.second.is_some() {
1974 return Err(Error::from(E::MissingTimeMinuteForSecond));
1975 }
1976 if self.subsec.is_some() {
1977 return Err(Error::from(E::MissingTimeMinuteForFractional));
1978 }
1979 return Time::new(hour, 0, 0, 0);
1980 };
1981 let Some(second) = self.second() else {
1982 if self.subsec.is_some() {
1983 return Err(Error::from(E::MissingTimeSecondForFractional));
1984 }
1985 return Time::new(hour, minute, 0, 0);
1986 };
1987 let Some(subsec) = self.subsec else {
1988 return Time::new(hour, minute, second, 0);
1989 };
1990 Time::new(hour, minute, second, subsec)
1991 }
1992
1993 /// Returns the parsed year, if available.
1994 ///
1995 /// This is also set when a 2 digit year is parsed. (But that's limited to
1996 /// the years 1969 to 2068, inclusive.)
1997 ///
1998 /// # Example
1999 ///
2000 /// This shows how to parse just a year:
2001 ///
2002 /// ```
2003 /// use jiff::fmt::strtime::BrokenDownTime;
2004 ///
2005 /// let tm = BrokenDownTime::parse("%Y", "2024")?;
2006 /// assert_eq!(tm.year(), Some(2024));
2007 ///
2008 /// # Ok::<(), Box<dyn std::error::Error>>(())
2009 /// ```
2010 ///
2011 /// And 2-digit years are supported too:
2012 ///
2013 /// ```
2014 /// use jiff::fmt::strtime::BrokenDownTime;
2015 ///
2016 /// let tm = BrokenDownTime::parse("%y", "24")?;
2017 /// assert_eq!(tm.year(), Some(2024));
2018 /// let tm = BrokenDownTime::parse("%y", "00")?;
2019 /// assert_eq!(tm.year(), Some(2000));
2020 /// let tm = BrokenDownTime::parse("%y", "69")?;
2021 /// assert_eq!(tm.year(), Some(1969));
2022 ///
2023 /// // 2-digit years have limited range. They must
2024 /// // be in the range 0-99.
2025 /// assert!(BrokenDownTime::parse("%y", "2024").is_err());
2026 ///
2027 /// # Ok::<(), Box<dyn std::error::Error>>(())
2028 /// ```
2029 #[inline]
2030 pub fn year(&self) -> Option<i16> {
2031 self.year
2032 }
2033
2034 /// Returns the parsed month, if available.
2035 ///
2036 /// # Example
2037 ///
2038 /// This shows a few different ways of parsing just a month:
2039 ///
2040 /// ```
2041 /// use jiff::fmt::strtime::BrokenDownTime;
2042 ///
2043 /// let tm = BrokenDownTime::parse("%m", "12")?;
2044 /// assert_eq!(tm.month(), Some(12));
2045 ///
2046 /// let tm = BrokenDownTime::parse("%B", "December")?;
2047 /// assert_eq!(tm.month(), Some(12));
2048 ///
2049 /// let tm = BrokenDownTime::parse("%b", "Dec")?;
2050 /// assert_eq!(tm.month(), Some(12));
2051 ///
2052 /// # Ok::<(), Box<dyn std::error::Error>>(())
2053 /// ```
2054 #[inline]
2055 pub fn month(&self) -> Option<i8> {
2056 self.month
2057 }
2058
2059 /// Returns the parsed day, if available.
2060 ///
2061 /// # Example
2062 ///
2063 /// This shows how to parse the day of the month:
2064 ///
2065 /// ```
2066 /// use jiff::fmt::strtime::BrokenDownTime;
2067 ///
2068 /// let tm = BrokenDownTime::parse("%d", "5")?;
2069 /// assert_eq!(tm.day(), Some(5));
2070 ///
2071 /// let tm = BrokenDownTime::parse("%d", "05")?;
2072 /// assert_eq!(tm.day(), Some(5));
2073 ///
2074 /// let tm = BrokenDownTime::parse("%03d", "005")?;
2075 /// assert_eq!(tm.day(), Some(5));
2076 ///
2077 /// // Parsing a day only works for all possible legal
2078 /// // values, even if, e.g., 31 isn't valid for all
2079 /// // possible year/month combinations.
2080 /// let tm = BrokenDownTime::parse("%d", "31")?;
2081 /// assert_eq!(tm.day(), Some(31));
2082 /// // This is true even if you're parsing a full date:
2083 /// let tm = BrokenDownTime::parse("%Y-%m-%d", "2024-04-31")?;
2084 /// assert_eq!(tm.day(), Some(31));
2085 /// // An error only occurs when you try to extract a date:
2086 /// assert!(tm.to_date().is_err());
2087 /// // But parsing a value that is always illegal will
2088 /// // result in an error:
2089 /// assert!(BrokenDownTime::parse("%d", "32").is_err());
2090 ///
2091 /// # Ok::<(), Box<dyn std::error::Error>>(())
2092 /// ```
2093 #[inline]
2094 pub fn day(&self) -> Option<i8> {
2095 self.day
2096 }
2097
2098 /// Returns the parsed day of the year (1-366), if available.
2099 ///
2100 /// # Example
2101 ///
2102 /// This shows how to parse the day of the year:
2103 ///
2104 /// ```
2105 /// use jiff::fmt::strtime::BrokenDownTime;
2106 ///
2107 /// let tm = BrokenDownTime::parse("%j", "5")?;
2108 /// assert_eq!(tm.day_of_year(), Some(5));
2109 /// assert_eq!(tm.to_string("%j")?, "005");
2110 /// assert_eq!(tm.to_string("%-j")?, "5");
2111 ///
2112 /// // Parsing the day of the year works for all possible legal
2113 /// // values, even if, e.g., 366 isn't valid for all possible
2114 /// // year/month combinations.
2115 /// let tm = BrokenDownTime::parse("%j", "366")?;
2116 /// assert_eq!(tm.day_of_year(), Some(366));
2117 /// // This is true even if you're parsing a year:
2118 /// let tm = BrokenDownTime::parse("%Y/%j", "2023/366")?;
2119 /// assert_eq!(tm.day_of_year(), Some(366));
2120 /// // An error only occurs when you try to extract a date:
2121 /// assert_eq!(
2122 /// tm.to_date().unwrap_err().to_string(),
2123 /// "invalid date: number of days for `2023` is invalid, \
2124 /// must be in range `1..=365`",
2125 /// );
2126 /// // But parsing a value that is always illegal will
2127 /// // result in an error:
2128 /// assert!(BrokenDownTime::parse("%j", "0").is_err());
2129 /// assert!(BrokenDownTime::parse("%j", "367").is_err());
2130 ///
2131 /// # Ok::<(), Box<dyn std::error::Error>>(())
2132 /// ```
2133 ///
2134 /// # Example: extract a [`Date`]
2135 ///
2136 /// This example shows how parsing a year and a day of the year enables
2137 /// the extraction of a date:
2138 ///
2139 /// ```
2140 /// use jiff::{civil::date, fmt::strtime::BrokenDownTime};
2141 ///
2142 /// let tm = BrokenDownTime::parse("%Y-%j", "2024-60")?;
2143 /// assert_eq!(tm.to_date()?, date(2024, 2, 29));
2144 ///
2145 /// # Ok::<(), Box<dyn std::error::Error>>(())
2146 /// ```
2147 ///
2148 /// When all of `%m`, `%d` and `%j` are used, then `%m` and `%d` take
2149 /// priority over `%j` when extracting a `Date` from a `BrokenDownTime`.
2150 /// However, `%j` is still parsed and accessible:
2151 ///
2152 /// ```
2153 /// use jiff::{civil::date, fmt::strtime::BrokenDownTime};
2154 ///
2155 /// let tm = BrokenDownTime::parse(
2156 /// "%Y-%m-%d (day of year: %j)",
2157 /// "2024-02-29 (day of year: 1)",
2158 /// )?;
2159 /// assert_eq!(tm.to_date()?, date(2024, 2, 29));
2160 /// assert_eq!(tm.day_of_year(), Some(1));
2161 ///
2162 /// # Ok::<(), Box<dyn std::error::Error>>(())
2163 /// ```
2164 #[inline]
2165 pub fn day_of_year(&self) -> Option<i16> {
2166 self.day_of_year
2167 }
2168
2169 /// Returns the parsed ISO 8601 week-based year, if available.
2170 ///
2171 /// This is also set when a 2 digit ISO 8601 week-based year is parsed.
2172 /// (But that's limited to the years 1969 to 2068, inclusive.)
2173 ///
2174 /// # Example
2175 ///
2176 /// This shows how to parse just an ISO 8601 week-based year:
2177 ///
2178 /// ```
2179 /// use jiff::fmt::strtime::BrokenDownTime;
2180 ///
2181 /// let tm = BrokenDownTime::parse("%G", "2024")?;
2182 /// assert_eq!(tm.iso_week_year(), Some(2024));
2183 ///
2184 /// # Ok::<(), Box<dyn std::error::Error>>(())
2185 /// ```
2186 ///
2187 /// And 2-digit years are supported too:
2188 ///
2189 /// ```
2190 /// use jiff::fmt::strtime::BrokenDownTime;
2191 ///
2192 /// let tm = BrokenDownTime::parse("%g", "24")?;
2193 /// assert_eq!(tm.iso_week_year(), Some(2024));
2194 /// let tm = BrokenDownTime::parse("%g", "00")?;
2195 /// assert_eq!(tm.iso_week_year(), Some(2000));
2196 /// let tm = BrokenDownTime::parse("%g", "69")?;
2197 /// assert_eq!(tm.iso_week_year(), Some(1969));
2198 ///
2199 /// // 2-digit years have limited range. They must
2200 /// // be in the range 0-99.
2201 /// assert!(BrokenDownTime::parse("%g", "2024").is_err());
2202 ///
2203 /// # Ok::<(), Box<dyn std::error::Error>>(())
2204 /// ```
2205 #[inline]
2206 pub fn iso_week_year(&self) -> Option<i16> {
2207 self.iso_week_year
2208 }
2209
2210 /// Returns the parsed ISO 8601 week-based number, if available.
2211 ///
2212 /// The week number is guaranteed to be in the range `1..53`. Week `1` is
2213 /// the first week of the year to contain 4 days.
2214 ///
2215 ///
2216 /// # Example
2217 ///
2218 /// This shows how to parse just an ISO 8601 week-based dates:
2219 ///
2220 /// ```
2221 /// use jiff::{civil::{Weekday, date}, fmt::strtime::BrokenDownTime};
2222 ///
2223 /// let tm = BrokenDownTime::parse("%G-W%V-%u", "2020-W01-1")?;
2224 /// assert_eq!(tm.iso_week_year(), Some(2020));
2225 /// assert_eq!(tm.iso_week(), Some(1));
2226 /// assert_eq!(tm.weekday(), Some(Weekday::Monday));
2227 /// assert_eq!(tm.to_date()?, date(2019, 12, 30));
2228 ///
2229 /// # Ok::<(), Box<dyn std::error::Error>>(())
2230 /// ```
2231 #[inline]
2232 pub fn iso_week(&self) -> Option<i8> {
2233 self.iso_week
2234 }
2235
2236 /// Returns the Sunday based week number.
2237 ///
2238 /// The week number returned is always in the range `0..=53`. Week `1`
2239 /// begins on the first Sunday of the year. Any days in the year prior to
2240 /// week `1` are in week `0`.
2241 ///
2242 /// # Example
2243 ///
2244 /// ```
2245 /// use jiff::{civil::{Weekday, date}, fmt::strtime::BrokenDownTime};
2246 ///
2247 /// let tm = BrokenDownTime::parse("%Y-%U-%w", "2025-01-0")?;
2248 /// assert_eq!(tm.year(), Some(2025));
2249 /// assert_eq!(tm.sunday_based_week(), Some(1));
2250 /// assert_eq!(tm.weekday(), Some(Weekday::Sunday));
2251 /// assert_eq!(tm.to_date()?, date(2025, 1, 5));
2252 ///
2253 /// # Ok::<(), Box<dyn std::error::Error>>(())
2254 /// ```
2255 #[inline]
2256 pub fn sunday_based_week(&self) -> Option<i8> {
2257 self.week_sun
2258 }
2259
2260 /// Returns the Monday based week number.
2261 ///
2262 /// The week number returned is always in the range `0..=53`. Week `1`
2263 /// begins on the first Monday of the year. Any days in the year prior to
2264 /// week `1` are in week `0`.
2265 ///
2266 /// # Example
2267 ///
2268 /// ```
2269 /// use jiff::{civil::{Weekday, date}, fmt::strtime::BrokenDownTime};
2270 ///
2271 /// let tm = BrokenDownTime::parse("%Y-%U-%w", "2025-01-1")?;
2272 /// assert_eq!(tm.year(), Some(2025));
2273 /// assert_eq!(tm.sunday_based_week(), Some(1));
2274 /// assert_eq!(tm.weekday(), Some(Weekday::Monday));
2275 /// assert_eq!(tm.to_date()?, date(2025, 1, 6));
2276 ///
2277 /// # Ok::<(), Box<dyn std::error::Error>>(())
2278 /// ```
2279 #[inline]
2280 pub fn monday_based_week(&self) -> Option<i8> {
2281 self.week_mon
2282 }
2283
2284 /// Returns the parsed hour, if available.
2285 ///
2286 /// The hour returned incorporates [`BrokenDownTime::meridiem`] if it's
2287 /// set. That is, if the actual parsed hour value is `1` but the meridiem
2288 /// is `PM`, then the hour returned by this method will be `13`.
2289 ///
2290 /// # Example
2291 ///
2292 /// This shows a how to parse an hour:
2293 ///
2294 /// ```
2295 /// use jiff::fmt::strtime::BrokenDownTime;
2296 ///
2297 /// let tm = BrokenDownTime::parse("%H", "13")?;
2298 /// assert_eq!(tm.hour(), Some(13));
2299 ///
2300 /// // When parsing a 12-hour clock without a
2301 /// // meridiem, the hour value is as parsed.
2302 /// let tm = BrokenDownTime::parse("%I", "1")?;
2303 /// assert_eq!(tm.hour(), Some(1));
2304 ///
2305 /// // If a meridiem is parsed, then it is used
2306 /// // to calculate the correct hour value.
2307 /// let tm = BrokenDownTime::parse("%I%P", "1pm")?;
2308 /// assert_eq!(tm.hour(), Some(13));
2309 ///
2310 /// // This works even if the hour and meridiem are
2311 /// // inconsistent with each other:
2312 /// let tm = BrokenDownTime::parse("%H%P", "13am")?;
2313 /// assert_eq!(tm.hour(), Some(1));
2314 ///
2315 /// # Ok::<(), Box<dyn std::error::Error>>(())
2316 /// ```
2317 #[inline]
2318 pub fn hour(&self) -> Option<i8> {
2319 self.hour
2320 }
2321
2322 /// Returns the parsed minute, if available.
2323 ///
2324 /// # Example
2325 ///
2326 /// This shows how to parse the minute:
2327 ///
2328 /// ```
2329 /// use jiff::fmt::strtime::BrokenDownTime;
2330 ///
2331 /// let tm = BrokenDownTime::parse("%M", "5")?;
2332 /// assert_eq!(tm.minute(), Some(5));
2333 ///
2334 /// # Ok::<(), Box<dyn std::error::Error>>(())
2335 /// ```
2336 #[inline]
2337 pub fn minute(&self) -> Option<i8> {
2338 self.minute
2339 }
2340
2341 /// Returns the parsed second, if available.
2342 ///
2343 /// # Example
2344 ///
2345 /// This shows how to parse the second:
2346 ///
2347 /// ```
2348 /// use jiff::fmt::strtime::BrokenDownTime;
2349 ///
2350 /// let tm = BrokenDownTime::parse("%S", "5")?;
2351 /// assert_eq!(tm.second(), Some(5));
2352 ///
2353 /// # Ok::<(), Box<dyn std::error::Error>>(())
2354 /// ```
2355 #[inline]
2356 pub fn second(&self) -> Option<i8> {
2357 self.second
2358 }
2359
2360 /// Returns the parsed subsecond nanosecond, if available.
2361 ///
2362 /// # Example
2363 ///
2364 /// This shows how to parse fractional seconds:
2365 ///
2366 /// ```
2367 /// use jiff::fmt::strtime::BrokenDownTime;
2368 ///
2369 /// let tm = BrokenDownTime::parse("%f", "123456")?;
2370 /// assert_eq!(tm.subsec_nanosecond(), Some(123_456_000));
2371 ///
2372 /// # Ok::<(), Box<dyn std::error::Error>>(())
2373 /// ```
2374 ///
2375 /// Note that when using `%.f`, the fractional component is optional!
2376 ///
2377 /// ```
2378 /// use jiff::fmt::strtime::BrokenDownTime;
2379 ///
2380 /// let tm = BrokenDownTime::parse("%S%.f", "1")?;
2381 /// assert_eq!(tm.second(), Some(1));
2382 /// assert_eq!(tm.subsec_nanosecond(), None);
2383 ///
2384 /// let tm = BrokenDownTime::parse("%S%.f", "1.789")?;
2385 /// assert_eq!(tm.second(), Some(1));
2386 /// assert_eq!(tm.subsec_nanosecond(), Some(789_000_000));
2387 ///
2388 /// # Ok::<(), Box<dyn std::error::Error>>(())
2389 /// ```
2390 #[inline]
2391 pub fn subsec_nanosecond(&self) -> Option<i32> {
2392 self.subsec
2393 }
2394
2395 /// Returns the parsed offset, if available.
2396 ///
2397 /// # Example
2398 ///
2399 /// This shows how to parse the offset:
2400 ///
2401 /// ```
2402 /// use jiff::{fmt::strtime::BrokenDownTime, tz::Offset};
2403 ///
2404 /// let tm = BrokenDownTime::parse("%z", "-0430")?;
2405 /// assert_eq!(
2406 /// tm.offset(),
2407 /// Some(Offset::from_seconds(-4 * 60 * 60 - 30 * 60).unwrap()),
2408 /// );
2409 /// let tm = BrokenDownTime::parse("%z", "-043059")?;
2410 /// assert_eq!(
2411 /// tm.offset(),
2412 /// Some(Offset::from_seconds(-4 * 60 * 60 - 30 * 60 - 59).unwrap()),
2413 /// );
2414 ///
2415 /// // Or, if you want colons:
2416 /// let tm = BrokenDownTime::parse("%:z", "-04:30")?;
2417 /// assert_eq!(
2418 /// tm.offset(),
2419 /// Some(Offset::from_seconds(-4 * 60 * 60 - 30 * 60).unwrap()),
2420 /// );
2421 ///
2422 /// # Ok::<(), Box<dyn std::error::Error>>(())
2423 /// ```
2424 #[inline]
2425 pub fn offset(&self) -> Option<Offset> {
2426 self.offset
2427 }
2428
2429 /// Returns the time zone IANA identifier, if available.
2430 ///
2431 /// Note that when `alloc` is disabled, this always returns `None`. (And
2432 /// there is no way to set it.)
2433 ///
2434 /// # Example
2435 ///
2436 /// This shows how to parse an IANA time zone identifier:
2437 ///
2438 /// ```
2439 /// use jiff::{fmt::strtime::BrokenDownTime, tz};
2440 ///
2441 /// let tm = BrokenDownTime::parse("%Q", "America/New_York")?;
2442 /// assert_eq!(tm.iana_time_zone(), Some("America/New_York"));
2443 /// assert_eq!(tm.offset(), None);
2444 ///
2445 /// // Note that %Q (and %:Q) also support parsing an offset
2446 /// // as a fallback. If that occurs, an IANA time zone
2447 /// // identifier is not available.
2448 /// let tm = BrokenDownTime::parse("%Q", "-0400")?;
2449 /// assert_eq!(tm.iana_time_zone(), None);
2450 /// assert_eq!(tm.offset(), Some(tz::offset(-4)));
2451 ///
2452 /// # Ok::<(), Box<dyn std::error::Error>>(())
2453 /// ```
2454 #[inline]
2455 pub fn iana_time_zone(&self) -> Option<&str> {
2456 #[cfg(feature = "alloc")]
2457 {
2458 if self.iana.is_none() && self.iana_from_tz {
2459 return self.tz.as_ref().and_then(|tz| tz.iana_name());
2460 }
2461 self.iana.as_deref()
2462 }
2463 #[cfg(not(feature = "alloc"))]
2464 {
2465 None
2466 }
2467 }
2468
2469 /// Returns the parsed weekday, if available.
2470 ///
2471 /// # Example
2472 ///
2473 /// This shows a few different ways of parsing just a weekday:
2474 ///
2475 /// ```
2476 /// use jiff::{civil::Weekday, fmt::strtime::BrokenDownTime};
2477 ///
2478 /// let tm = BrokenDownTime::parse("%A", "Saturday")?;
2479 /// assert_eq!(tm.weekday(), Some(Weekday::Saturday));
2480 ///
2481 /// let tm = BrokenDownTime::parse("%a", "Sat")?;
2482 /// assert_eq!(tm.weekday(), Some(Weekday::Saturday));
2483 ///
2484 /// // A weekday is only available if it is explicitly parsed!
2485 /// let tm = BrokenDownTime::parse("%F", "2024-07-27")?;
2486 /// assert_eq!(tm.weekday(), None);
2487 /// // If you need a weekday derived from a parsed date, then:
2488 /// assert_eq!(tm.to_date()?.weekday(), Weekday::Saturday);
2489 ///
2490 /// # Ok::<(), Box<dyn std::error::Error>>(())
2491 /// ```
2492 ///
2493 /// Note that this will return the parsed weekday even if
2494 /// it's inconsistent with a parsed date:
2495 ///
2496 /// ```
2497 /// use jiff::{civil::{Weekday, date}, fmt::strtime::BrokenDownTime};
2498 ///
2499 /// let mut tm = BrokenDownTime::parse("%a, %F", "Wed, 2024-07-27")?;
2500 /// // 2024-07-27 is a Saturday, but Wednesday was parsed:
2501 /// assert_eq!(tm.weekday(), Some(Weekday::Wednesday));
2502 /// // An error only occurs when extracting a date:
2503 /// assert!(tm.to_date().is_err());
2504 /// // To skip the weekday, error checking, zero it out first:
2505 /// tm.set_weekday(None);
2506 /// assert_eq!(tm.to_date()?, date(2024, 7, 27));
2507 ///
2508 /// # Ok::<(), Box<dyn std::error::Error>>(())
2509 /// ```
2510 #[inline]
2511 pub fn weekday(&self) -> Option<Weekday> {
2512 self.weekday
2513 }
2514
2515 /// Returns the parsed meridiem, if available.
2516 ///
2517 /// When there is a conflict between the meridiem and the hour value, the
2518 /// meridiem takes precedence.
2519 ///
2520 /// # Example
2521 ///
2522 /// This shows a how to parse the meridiem:
2523 ///
2524 /// ```
2525 /// use jiff::fmt::strtime::{BrokenDownTime, Meridiem};
2526 ///
2527 /// let tm = BrokenDownTime::parse("%p", "AM")?;
2528 /// assert_eq!(tm.meridiem(), Some(Meridiem::AM));
2529 /// let tm = BrokenDownTime::parse("%P", "pm")?;
2530 /// assert_eq!(tm.meridiem(), Some(Meridiem::PM));
2531 ///
2532 /// // A meridiem takes precedence.
2533 /// let tm = BrokenDownTime::parse("%H%P", "13am")?;
2534 /// assert_eq!(tm.hour(), Some(1));
2535 /// assert_eq!(tm.meridiem(), Some(Meridiem::AM));
2536 ///
2537 /// # Ok::<(), Box<dyn std::error::Error>>(())
2538 /// ```
2539 #[inline]
2540 pub fn meridiem(&self) -> Option<Meridiem> {
2541 self.meridiem
2542 }
2543
2544 /// Returns the parsed timestamp, if available.
2545 ///
2546 /// Unlike [`BrokenDownTime::to_timestamp`], this only returns a timestamp
2547 /// that has been set explicitly via [`BrokenDownTime::set_timestamp`].
2548 /// For example, this occurs when parsing a `%s` conversion specifier.
2549 ///
2550 /// # Example
2551 ///
2552 /// This shows a how to parse the timestamp:
2553 ///
2554 /// ```
2555 /// use jiff::{fmt::strtime::BrokenDownTime, Timestamp};
2556 ///
2557 /// let tm = BrokenDownTime::parse("%s", "1760723100")?;
2558 /// assert_eq!(tm.timestamp(), Some(Timestamp::constant(1760723100, 0)));
2559 ///
2560 /// # Ok::<(), Box<dyn std::error::Error>>(())
2561 /// ```
2562 ///
2563 /// # Example: difference between `timestamp` and `to_timestamp`
2564 ///
2565 /// This shows how [`BrokenDownTime::to_timestamp`] will try to return
2566 /// a timestamp when one could be formed from other data, while
2567 /// [`BrokenDownTime::timestamp`] only returns a timestamp that has been
2568 /// explicitly set.
2569 ///
2570 /// ```
2571 /// use jiff::{fmt::strtime::BrokenDownTime, tz, Timestamp};
2572 ///
2573 /// let mut tm = BrokenDownTime::default();
2574 /// tm.set_year(Some(2025))?;
2575 /// tm.set_month(Some(10))?;
2576 /// tm.set_day(Some(17))?;
2577 /// tm.set_hour(Some(13))?;
2578 /// tm.set_minute(Some(45))?;
2579 /// tm.set_offset(Some(tz::offset(-4)));
2580 /// assert_eq!(tm.to_timestamp()?, Timestamp::constant(1760723100, 0));
2581 /// // No timestamp set!
2582 /// assert_eq!(tm.timestamp(), None);
2583 /// // A timestamp can be set, and it may not be consistent
2584 /// // with other data in `BrokenDownTime`.
2585 /// tm.set_timestamp(Some(Timestamp::UNIX_EPOCH));
2586 /// assert_eq!(tm.timestamp(), Some(Timestamp::UNIX_EPOCH));
2587 /// // And note that `BrokenDownTime::to_timestamp` will prefer
2588 /// // an explicitly set timestamp whenever possible.
2589 /// assert_eq!(tm.to_timestamp()?, Timestamp::UNIX_EPOCH);
2590 ///
2591 /// # Ok::<(), Box<dyn std::error::Error>>(())
2592 /// ```
2593 #[inline]
2594 pub fn timestamp(&self) -> Option<Timestamp> {
2595 self.timestamp
2596 }
2597
2598 /// Set the year on this broken down time.
2599 ///
2600 /// # Errors
2601 ///
2602 /// This returns an error if the given year is out of range.
2603 ///
2604 /// # Example
2605 ///
2606 /// ```
2607 /// use jiff::fmt::strtime::BrokenDownTime;
2608 ///
2609 /// let mut tm = BrokenDownTime::default();
2610 /// // out of range
2611 /// assert!(tm.set_year(Some(10_000)).is_err());
2612 /// tm.set_year(Some(2024))?;
2613 /// assert_eq!(tm.to_string("%Y")?, "2024");
2614 ///
2615 /// # Ok::<(), Box<dyn std::error::Error>>(())
2616 /// ```
2617 #[inline]
2618 pub fn set_year(&mut self, year: Option<i16>) -> Result<(), Error> {
2619 self.year = year.map(b::Year::check).transpose()?;
2620 Ok(())
2621 }
2622
2623 /// Set the month on this broken down time.
2624 ///
2625 /// # Errors
2626 ///
2627 /// This returns an error if the given month is out of range.
2628 ///
2629 /// # Example
2630 ///
2631 /// ```
2632 /// use jiff::fmt::strtime::BrokenDownTime;
2633 ///
2634 /// let mut tm = BrokenDownTime::default();
2635 /// // out of range
2636 /// assert!(tm.set_month(Some(0)).is_err());
2637 /// tm.set_month(Some(12))?;
2638 /// assert_eq!(tm.to_string("%B")?, "December");
2639 ///
2640 /// # Ok::<(), Box<dyn std::error::Error>>(())
2641 /// ```
2642 #[inline]
2643 pub fn set_month(&mut self, month: Option<i8>) -> Result<(), Error> {
2644 self.month = month.map(b::Month::check).transpose()?;
2645 Ok(())
2646 }
2647
2648 /// Set the day on this broken down time.
2649 ///
2650 /// # Errors
2651 ///
2652 /// This returns an error if the given day is out of range.
2653 ///
2654 /// Note that setting a day to a value that is legal in any context is
2655 /// always valid, even if it isn't valid for the year and month
2656 /// components already set.
2657 ///
2658 /// # Example
2659 ///
2660 /// ```
2661 /// use jiff::fmt::strtime::BrokenDownTime;
2662 ///
2663 /// let mut tm = BrokenDownTime::default();
2664 /// // out of range
2665 /// assert!(tm.set_day(Some(32)).is_err());
2666 /// tm.set_day(Some(31))?;
2667 /// assert_eq!(tm.to_string("%d")?, "31");
2668 ///
2669 /// // Works even if the resulting date is invalid.
2670 /// let mut tm = BrokenDownTime::default();
2671 /// tm.set_year(Some(2024))?;
2672 /// tm.set_month(Some(4))?;
2673 /// tm.set_day(Some(31))?; // April has 30 days, not 31
2674 /// assert_eq!(tm.to_string("%F")?, "2024-04-31");
2675 ///
2676 /// # Ok::<(), Box<dyn std::error::Error>>(())
2677 /// ```
2678 #[inline]
2679 pub fn set_day(&mut self, day: Option<i8>) -> Result<(), Error> {
2680 self.day = day.map(b::Day::check).transpose()?;
2681 Ok(())
2682 }
2683
2684 /// Set the day of year on this broken down time.
2685 ///
2686 /// # Errors
2687 ///
2688 /// This returns an error if the given day is out of range.
2689 ///
2690 /// Note that setting a day to a value that is legal in any context
2691 /// is always valid, even if it isn't valid for the year, month and
2692 /// day-of-month components already set.
2693 ///
2694 /// # Example
2695 ///
2696 /// ```
2697 /// use jiff::fmt::strtime::BrokenDownTime;
2698 ///
2699 /// let mut tm = BrokenDownTime::default();
2700 /// // out of range
2701 /// assert!(tm.set_day_of_year(Some(367)).is_err());
2702 /// tm.set_day_of_year(Some(31))?;
2703 /// assert_eq!(tm.to_string("%j")?, "031");
2704 ///
2705 /// // Works even if the resulting date is invalid.
2706 /// let mut tm = BrokenDownTime::default();
2707 /// tm.set_year(Some(2023))?;
2708 /// tm.set_day_of_year(Some(366))?; // 2023 wasn't a leap year
2709 /// assert_eq!(tm.to_string("%Y/%j")?, "2023/366");
2710 ///
2711 /// # Ok::<(), Box<dyn std::error::Error>>(())
2712 /// ```
2713 #[inline]
2714 pub fn set_day_of_year(&mut self, day: Option<i16>) -> Result<(), Error> {
2715 self.day_of_year = day.map(b::DayOfYear::check).transpose()?;
2716 Ok(())
2717 }
2718
2719 /// Set the ISO 8601 week-based year on this broken down time.
2720 ///
2721 /// # Errors
2722 ///
2723 /// This returns an error if the given year is out of range.
2724 ///
2725 /// # Example
2726 ///
2727 /// ```
2728 /// use jiff::fmt::strtime::BrokenDownTime;
2729 ///
2730 /// let mut tm = BrokenDownTime::default();
2731 /// // out of range
2732 /// assert!(tm.set_iso_week_year(Some(10_000)).is_err());
2733 /// tm.set_iso_week_year(Some(2024))?;
2734 /// assert_eq!(tm.to_string("%G")?, "2024");
2735 ///
2736 /// # Ok::<(), Box<dyn std::error::Error>>(())
2737 /// ```
2738 #[inline]
2739 pub fn set_iso_week_year(
2740 &mut self,
2741 year: Option<i16>,
2742 ) -> Result<(), Error> {
2743 self.iso_week_year = year.map(b::ISOYear::check).transpose()?;
2744 Ok(())
2745 }
2746
2747 /// Set the ISO 8601 week-based number on this broken down time.
2748 ///
2749 /// The week number must be in the range `1..53`. Week `1` is
2750 /// the first week of the year to contain 4 days.
2751 ///
2752 /// # Errors
2753 ///
2754 /// This returns an error if the given week number is out of range.
2755 ///
2756 /// # Example
2757 ///
2758 /// ```
2759 /// use jiff::{civil::Weekday, fmt::strtime::BrokenDownTime};
2760 ///
2761 /// let mut tm = BrokenDownTime::default();
2762 /// // out of range
2763 /// assert!(tm.set_iso_week(Some(0)).is_err());
2764 /// // out of range
2765 /// assert!(tm.set_iso_week(Some(54)).is_err());
2766 ///
2767 /// tm.set_iso_week_year(Some(2020))?;
2768 /// tm.set_iso_week(Some(1))?;
2769 /// tm.set_weekday(Some(Weekday::Monday));
2770 /// assert_eq!(tm.to_string("%G-W%V-%u")?, "2020-W01-1");
2771 /// assert_eq!(tm.to_string("%F")?, "2019-12-30");
2772 ///
2773 /// # Ok::<(), Box<dyn std::error::Error>>(())
2774 /// ```
2775 #[inline]
2776 pub fn set_iso_week(
2777 &mut self,
2778 week_number: Option<i8>,
2779 ) -> Result<(), Error> {
2780 self.iso_week = week_number.map(b::ISOWeek::check).transpose()?;
2781 Ok(())
2782 }
2783
2784 /// Set the Sunday based week number.
2785 ///
2786 /// The week number returned is always in the range `0..=53`. Week `1`
2787 /// begins on the first Sunday of the year. Any days in the year prior to
2788 /// week `1` are in week `0`.
2789 ///
2790 /// # Example
2791 ///
2792 /// ```
2793 /// use jiff::fmt::strtime::BrokenDownTime;
2794 ///
2795 /// let mut tm = BrokenDownTime::default();
2796 /// // out of range
2797 /// assert!(tm.set_sunday_based_week(Some(56)).is_err());
2798 /// tm.set_sunday_based_week(Some(9))?;
2799 /// assert_eq!(tm.to_string("%U")?, "09");
2800 ///
2801 /// # Ok::<(), Box<dyn std::error::Error>>(())
2802 /// ```
2803 #[inline]
2804 pub fn set_sunday_based_week(
2805 &mut self,
2806 week_number: Option<i8>,
2807 ) -> Result<(), Error> {
2808 self.week_sun = week_number.map(b::WeekNum::check).transpose()?;
2809 Ok(())
2810 }
2811
2812 /// Set the Monday based week number.
2813 ///
2814 /// The week number returned is always in the range `0..=53`. Week `1`
2815 /// begins on the first Monday of the year. Any days in the year prior to
2816 /// week `1` are in week `0`.
2817 ///
2818 /// # Example
2819 ///
2820 /// ```
2821 /// use jiff::fmt::strtime::BrokenDownTime;
2822 ///
2823 /// let mut tm = BrokenDownTime::default();
2824 /// // out of range
2825 /// assert!(tm.set_monday_based_week(Some(56)).is_err());
2826 /// tm.set_monday_based_week(Some(9))?;
2827 /// assert_eq!(tm.to_string("%W")?, "09");
2828 ///
2829 /// # Ok::<(), Box<dyn std::error::Error>>(())
2830 /// ```
2831 #[inline]
2832 pub fn set_monday_based_week(
2833 &mut self,
2834 week_number: Option<i8>,
2835 ) -> Result<(), Error> {
2836 self.week_mon = week_number.map(b::WeekNum::check).transpose()?;
2837 Ok(())
2838 }
2839
2840 /// Set the hour on this broken down time.
2841 ///
2842 /// # Errors
2843 ///
2844 /// This returns an error if the given hour is out of range.
2845 ///
2846 /// # Example
2847 ///
2848 /// ```
2849 /// use jiff::fmt::strtime::BrokenDownTime;
2850 ///
2851 /// let mut tm = BrokenDownTime::default();
2852 /// // out of range
2853 /// assert!(tm.set_hour(Some(24)).is_err());
2854 /// tm.set_hour(Some(0))?;
2855 /// assert_eq!(tm.to_string("%H")?, "00");
2856 /// assert_eq!(tm.to_string("%-H")?, "0");
2857 ///
2858 /// # Ok::<(), Box<dyn std::error::Error>>(())
2859 /// ```
2860 #[inline]
2861 pub fn set_hour(&mut self, hour: Option<i8>) -> Result<(), Error> {
2862 self.hour = hour.map(b::Hour::check).transpose()?;
2863 if let Some(meridiem) = self.meridiem {
2864 self.hour = self.hour.map(|hour| meridiem.adjust_hour(hour));
2865 }
2866 Ok(())
2867 }
2868
2869 /// Set the minute on this broken down time.
2870 ///
2871 /// # Errors
2872 ///
2873 /// This returns an error if the given minute is out of range.
2874 ///
2875 /// # Example
2876 ///
2877 /// ```
2878 /// use jiff::fmt::strtime::BrokenDownTime;
2879 ///
2880 /// let mut tm = BrokenDownTime::default();
2881 /// // out of range
2882 /// assert!(tm.set_minute(Some(60)).is_err());
2883 /// tm.set_minute(Some(59))?;
2884 /// assert_eq!(tm.to_string("%M")?, "59");
2885 /// assert_eq!(tm.to_string("%03M")?, "059");
2886 /// assert_eq!(tm.to_string("%_3M")?, " 59");
2887 ///
2888 /// # Ok::<(), Box<dyn std::error::Error>>(())
2889 /// ```
2890 #[inline]
2891 pub fn set_minute(&mut self, minute: Option<i8>) -> Result<(), Error> {
2892 self.minute = minute.map(b::Minute::check).transpose()?;
2893 Ok(())
2894 }
2895
2896 /// Set the second on this broken down time.
2897 ///
2898 /// # Errors
2899 ///
2900 /// This returns an error if the given second is out of range.
2901 ///
2902 /// Jiff does not support leap seconds, so the range of valid seconds is
2903 /// `0` to `59`, inclusive. Note though that when parsing, a parsed value
2904 /// of `60` is automatically constrained to `59`.
2905 ///
2906 /// # Example
2907 ///
2908 /// ```
2909 /// use jiff::fmt::strtime::BrokenDownTime;
2910 ///
2911 /// let mut tm = BrokenDownTime::default();
2912 /// // out of range
2913 /// assert!(tm.set_second(Some(60)).is_err());
2914 /// tm.set_second(Some(59))?;
2915 /// assert_eq!(tm.to_string("%S")?, "59");
2916 ///
2917 /// # Ok::<(), Box<dyn std::error::Error>>(())
2918 /// ```
2919 #[inline]
2920 pub fn set_second(&mut self, second: Option<i8>) -> Result<(), Error> {
2921 self.second = second.map(b::Second::check).transpose()?;
2922 Ok(())
2923 }
2924
2925 /// Set the subsecond nanosecond on this broken down time.
2926 ///
2927 /// # Errors
2928 ///
2929 /// This returns an error if the given number of nanoseconds is out of
2930 /// range. It must be non-negative and less than 1 whole second.
2931 ///
2932 /// # Example
2933 ///
2934 /// ```
2935 /// use jiff::fmt::strtime::BrokenDownTime;
2936 ///
2937 /// let mut tm = BrokenDownTime::default();
2938 /// // out of range
2939 /// assert!(tm.set_subsec_nanosecond(Some(1_000_000_000)).is_err());
2940 /// tm.set_subsec_nanosecond(Some(123_000_000))?;
2941 /// assert_eq!(tm.to_string("%f")?, "123");
2942 /// assert_eq!(tm.to_string("%.6f")?, ".123000");
2943 ///
2944 /// # Ok::<(), Box<dyn std::error::Error>>(())
2945 /// ```
2946 #[inline]
2947 pub fn set_subsec_nanosecond(
2948 &mut self,
2949 subsec_nanosecond: Option<i32>,
2950 ) -> Result<(), Error> {
2951 self.subsec =
2952 subsec_nanosecond.map(b::SubsecNanosecond::check).transpose()?;
2953 Ok(())
2954 }
2955
2956 /// Set the time zone offset on this broken down time.
2957 ///
2958 /// This can be useful for setting the offset after parsing if the offset
2959 /// is known from the context or from some out-of-band information.
2960 ///
2961 /// Note that one can set any legal offset value, regardless of whether
2962 /// it's consistent with the IANA time zone identifier on this broken down
2963 /// time (if it's set). Similarly, setting the offset does not actually
2964 /// change any other value in this broken down time.
2965 ///
2966 /// # Example: setting the offset after parsing
2967 ///
2968 /// One use case for this routine is when parsing a datetime _without_
2969 /// an offset, but where one wants to set an offset based on the context.
2970 /// For example, while it's usually not correct to assume a datetime is
2971 /// in UTC, if you know it is, then you can parse it into a [`Timestamp`]
2972 /// like so:
2973 ///
2974 /// ```
2975 /// use jiff::{fmt::strtime::BrokenDownTime, tz::Offset};
2976 ///
2977 /// let mut tm = BrokenDownTime::parse(
2978 /// "%Y-%m-%d at %H:%M:%S",
2979 /// "1970-01-01 at 01:00:00",
2980 /// )?;
2981 /// tm.set_offset(Some(Offset::UTC));
2982 /// // Normally this would fail since the parse
2983 /// // itself doesn't include an offset. It only
2984 /// // works here because we explicitly set the
2985 /// // offset after parsing.
2986 /// assert_eq!(tm.to_timestamp()?.to_string(), "1970-01-01T01:00:00Z");
2987 ///
2988 /// # Ok::<(), Box<dyn std::error::Error>>(())
2989 /// ```
2990 ///
2991 /// # Example: setting the offset is not "smart"
2992 ///
2993 /// This example shows how setting the offset on an existing broken down
2994 /// time does not impact any other field, even if the result printed is
2995 /// non-sensical:
2996 ///
2997 /// ```
2998 /// use jiff::{civil::date, fmt::strtime::BrokenDownTime, tz};
2999 ///
3000 /// let zdt = date(2024, 8, 28)
3001 /// .at(14, 56, 0, 0)
3002 /// .in_tz("America/New_York")?;
3003 /// let mut tm = BrokenDownTime::from(&zdt);
3004 /// tm.set_offset(Some(tz::offset(12)));
3005 /// assert_eq!(
3006 /// tm.to_string("%Y-%m-%d at %H:%M:%S in %Q %:z")?,
3007 /// "2024-08-28 at 14:56:00 in America/New_York +12:00",
3008 /// );
3009 ///
3010 /// # Ok::<(), Box<dyn std::error::Error>>(())
3011 /// ```
3012 #[inline]
3013 pub fn set_offset(&mut self, offset: Option<Offset>) {
3014 self.offset = offset;
3015 }
3016
3017 /// Set the IANA time zone identifier on this broken down time.
3018 ///
3019 /// This can be useful for setting the time zone after parsing if the time
3020 /// zone is known from the context or from some out-of-band information.
3021 ///
3022 /// Note that one can set any string value, regardless of whether it's
3023 /// consistent with the offset on this broken down time (if it's set).
3024 /// Similarly, setting the IANA time zone identifier does not actually
3025 /// change any other value in this broken down time.
3026 ///
3027 /// # Example: setting the IANA time zone identifier after parsing
3028 ///
3029 /// One use case for this routine is when parsing a datetime _without_ a
3030 /// time zone, but where one wants to set a time zone based on the context.
3031 ///
3032 /// ```
3033 /// use jiff::{fmt::strtime::BrokenDownTime};
3034 ///
3035 /// let mut tm = BrokenDownTime::parse(
3036 /// "%Y-%m-%d at %H:%M:%S",
3037 /// "1970-01-01 at 01:00:00",
3038 /// )?;
3039 /// tm.set_iana_time_zone(Some(String::from("America/New_York")));
3040 /// // Normally this would fail since the parse
3041 /// // itself doesn't include an offset or a time
3042 /// // zone. It only works here because we
3043 /// // explicitly set the time zone after parsing.
3044 /// assert_eq!(
3045 /// tm.to_zoned_datetime()?.to_string(),
3046 /// "1970-01-01T01:00:00-05:00[America/New_York]",
3047 /// );
3048 ///
3049 /// # Ok::<(), Box<dyn std::error::Error>>(())
3050 /// ```
3051 ///
3052 /// # Example: setting the IANA time zone identifier is not "smart"
3053 ///
3054 /// This example shows how setting the IANA time zone identifier on an
3055 /// existing broken down time does not impact any other field, even if the
3056 /// result printed is non-sensical:
3057 ///
3058 /// ```
3059 /// use jiff::{civil::date, fmt::strtime::BrokenDownTime};
3060 ///
3061 /// let zdt = date(2024, 8, 28)
3062 /// .at(14, 56, 0, 0)
3063 /// .in_tz("America/New_York")?;
3064 /// let mut tm = BrokenDownTime::from(&zdt);
3065 /// tm.set_iana_time_zone(Some(String::from("Australia/Hobart")));
3066 /// assert_eq!(
3067 /// tm.to_string("%Y-%m-%d at %H:%M:%S in %Q %:z")?,
3068 /// "2024-08-28 at 14:56:00 in Australia/Hobart -04:00",
3069 /// );
3070 ///
3071 /// // In fact, it's not even required that the string
3072 /// // given be a valid IANA time zone identifier!
3073 /// let mut tm = BrokenDownTime::from(&zdt);
3074 /// tm.set_iana_time_zone(Some(String::from("Clearly/Invalid")));
3075 /// assert_eq!(
3076 /// tm.to_string("%Y-%m-%d at %H:%M:%S in %Q %:z")?,
3077 /// "2024-08-28 at 14:56:00 in Clearly/Invalid -04:00",
3078 /// );
3079 ///
3080 /// # Ok::<(), Box<dyn std::error::Error>>(())
3081 /// ```
3082 #[cfg(feature = "alloc")]
3083 #[inline]
3084 pub fn set_iana_time_zone(&mut self, id: Option<alloc::string::String>) {
3085 self.iana = id;
3086 self.iana_from_tz = false;
3087 }
3088
3089 /// Set the weekday on this broken down time.
3090 ///
3091 /// # Example
3092 ///
3093 /// ```
3094 /// use jiff::{civil::Weekday, fmt::strtime::BrokenDownTime};
3095 ///
3096 /// let mut tm = BrokenDownTime::default();
3097 /// tm.set_weekday(Some(Weekday::Saturday));
3098 /// assert_eq!(tm.to_string("%A")?, "Saturday");
3099 /// assert_eq!(tm.to_string("%a")?, "Sat");
3100 /// assert_eq!(tm.to_string("%^a")?, "SAT");
3101 ///
3102 /// # Ok::<(), Box<dyn std::error::Error>>(())
3103 /// ```
3104 ///
3105 /// Note that one use case for this routine is to enable parsing of
3106 /// weekdays in datetime, but skip checking that the weekday is valid for
3107 /// the parsed date.
3108 ///
3109 /// ```
3110 /// use jiff::{civil::date, fmt::strtime::BrokenDownTime};
3111 ///
3112 /// let mut tm = BrokenDownTime::parse("%a, %F", "Wed, 2024-07-27")?;
3113 /// // 2024-07-27 was a Saturday, so asking for a date fails:
3114 /// assert!(tm.to_date().is_err());
3115 /// // But we can remove the weekday from our broken down time:
3116 /// tm.set_weekday(None);
3117 /// assert_eq!(tm.to_date()?, date(2024, 7, 27));
3118 ///
3119 /// # Ok::<(), Box<dyn std::error::Error>>(())
3120 /// ```
3121 ///
3122 /// The advantage of this approach is that it still ensures the parsed
3123 /// weekday is a valid weekday (for example, `Wat` will cause parsing to
3124 /// fail), but doesn't require it to be consistent with the date. This
3125 /// is useful for interacting with systems that don't do strict error
3126 /// checking.
3127 #[inline]
3128 pub fn set_weekday(&mut self, weekday: Option<Weekday>) {
3129 self.weekday = weekday;
3130 }
3131
3132 /// Set the meridiem (AM/PM). This is most useful when doing custom
3133 /// parsing that involves 12-hour time.
3134 ///
3135 /// When there is a conflict between the meridiem and the hour value, the
3136 /// meridiem takes precedence.
3137 ///
3138 /// # Example
3139 ///
3140 /// This shows how to set a meridiem and its impact on the hour value:
3141 ///
3142 /// ```
3143 /// use jiff::{fmt::strtime::{BrokenDownTime, Meridiem}};
3144 ///
3145 /// let mut tm = BrokenDownTime::default();
3146 /// tm.set_hour(Some(3))?;
3147 /// tm.set_meridiem(Some(Meridiem::PM));
3148 /// let time = tm.to_time()?;
3149 /// assert_eq!(time.hour(), 15); // 3:00 PM = 15:00 in 24-hour time
3150 ///
3151 /// # Ok::<(), Box<dyn std::error::Error>>(())
3152 /// ```
3153 ///
3154 /// This shows how setting a meridiem influences formatting:
3155 ///
3156 /// ```
3157 /// use jiff::{fmt::strtime::{BrokenDownTime, Meridiem}};
3158 ///
3159 /// let mut tm = BrokenDownTime::default();
3160 /// tm.set_hour(Some(3))?;
3161 /// tm.set_minute(Some(4))?;
3162 /// tm.set_second(Some(5))?;
3163 /// tm.set_meridiem(Some(Meridiem::PM));
3164 /// assert_eq!(tm.to_string("%T")?, "15:04:05");
3165 ///
3166 /// # Ok::<(), Box<dyn std::error::Error>>(())
3167 /// ```
3168 ///
3169 /// And this shows how a conflict between the hour and meridiem is
3170 /// handled. Notably, the set meridiem still applies.
3171 ///
3172 /// ```
3173 /// use jiff::{fmt::strtime::{BrokenDownTime, Meridiem}};
3174 ///
3175 /// let mut tm = BrokenDownTime::default();
3176 /// tm.set_hour(Some(13))?;
3177 /// tm.set_minute(Some(4))?;
3178 /// tm.set_second(Some(5))?;
3179 /// tm.set_meridiem(Some(Meridiem::AM));
3180 /// assert_eq!(tm.to_string("%T")?, "01:04:05");
3181 ///
3182 /// # Ok::<(), Box<dyn std::error::Error>>(())
3183 /// ```
3184 #[inline]
3185 pub fn set_meridiem(&mut self, meridiem: Option<Meridiem>) {
3186 if let Some(meridiem) = meridiem {
3187 self.hour = self.hour.map(|hour| meridiem.adjust_hour(hour));
3188 }
3189 self.meridiem = meridiem;
3190 }
3191
3192 /// Set an explicit timestamp for this `BrokenDownTime`.
3193 ///
3194 /// An explicitly set timestamp takes precedence when using higher
3195 /// level convenience accessors such as [`BrokenDownTime::to_timestamp`]
3196 /// and [`BrokenDownTime::to_zoned_datetime`].
3197 ///
3198 /// # Example
3199 ///
3200 /// This shows how [`BrokenDownTime::to_timestamp`] will try to return
3201 /// a timestamp when one could be formed from other data, while
3202 /// [`BrokenDownTime::timestamp`] only returns a timestamp that has been
3203 /// explicitly set.
3204 ///
3205 /// ```
3206 /// use jiff::{fmt::strtime::BrokenDownTime, tz, Timestamp};
3207 ///
3208 /// let mut tm = BrokenDownTime::default();
3209 /// tm.set_year(Some(2025))?;
3210 /// tm.set_month(Some(10))?;
3211 /// tm.set_day(Some(17))?;
3212 /// tm.set_hour(Some(13))?;
3213 /// tm.set_minute(Some(45))?;
3214 /// tm.set_offset(Some(tz::offset(-4)));
3215 /// assert_eq!(tm.to_timestamp()?, Timestamp::constant(1760723100, 0));
3216 /// // No timestamp set!
3217 /// assert_eq!(tm.timestamp(), None);
3218 /// // A timestamp can be set, and it may not be consistent
3219 /// // with other data in `BrokenDownTime`.
3220 /// tm.set_timestamp(Some(Timestamp::UNIX_EPOCH));
3221 /// assert_eq!(tm.timestamp(), Some(Timestamp::UNIX_EPOCH));
3222 /// // And note that `BrokenDownTime::to_timestamp` will prefer
3223 /// // an explicitly set timestamp whenever possible.
3224 /// assert_eq!(tm.to_timestamp()?, Timestamp::UNIX_EPOCH);
3225 ///
3226 /// # Ok::<(), Box<dyn std::error::Error>>(())
3227 /// ```
3228 #[inline]
3229 pub fn set_timestamp(&mut self, timestamp: Option<Timestamp>) {
3230 self.timestamp = timestamp;
3231 }
3232}
3233
3234impl<'a> From<&'a ZonedDateTime> for BrokenDownTime {
3235 fn from(zdt: &'a ZonedDateTime) -> BrokenDownTime {
3236 // let offset_info = zdt.time_zone().to_offset_info(zdt.timestamp());
3237 BrokenDownTime {
3238 offset: Some(zdt.offset()),
3239 timestamp: Some(zdt.timestamp()),
3240 tz: Some(zdt.time_zone().clone()),
3241 #[cfg(feature = "alloc")]
3242 iana_from_tz: true,
3243 ..BrokenDownTime::from(zdt.datetime())
3244 }
3245 }
3246}
3247
3248impl From<Timestamp> for BrokenDownTime {
3249 fn from(ts: Timestamp) -> BrokenDownTime {
3250 let dt = Offset::UTC.to_datetime(ts);
3251 BrokenDownTime {
3252 offset: Some(Offset::UTC),
3253 timestamp: Some(ts),
3254 tz: Some(TimeZone::UTC),
3255 ..BrokenDownTime::from(dt)
3256 }
3257 }
3258}
3259
3260impl From<DateTime> for BrokenDownTime {
3261 fn from(dt: DateTime) -> BrokenDownTime {
3262 let (d, t) = (dt.date(), dt.time());
3263 BrokenDownTime {
3264 year: Some(d.year()),
3265 month: Some(d.month()),
3266 day: Some(d.day()),
3267 hour: Some(t.hour()),
3268 minute: Some(t.minute()),
3269 second: Some(t.second()),
3270 subsec: Some(t.subsec_nanosecond()),
3271 meridiem: Some(Meridiem::from(t)),
3272 ..BrokenDownTime::default()
3273 }
3274 }
3275}
3276
3277impl From<Date> for BrokenDownTime {
3278 fn from(d: Date) -> BrokenDownTime {
3279 BrokenDownTime {
3280 year: Some(d.year()),
3281 month: Some(d.month()),
3282 day: Some(d.day()),
3283 ..BrokenDownTime::default()
3284 }
3285 }
3286}
3287
3288impl From<ISOWeekDate> for BrokenDownTime {
3289 fn from(wd: ISOWeekDate) -> BrokenDownTime {
3290 BrokenDownTime {
3291 iso_week_year: Some(wd.year()),
3292 iso_week: Some(wd.week()),
3293 weekday: Some(wd.weekday()),
3294 ..BrokenDownTime::default()
3295 }
3296 }
3297}
3298
3299impl From<Time> for BrokenDownTime {
3300 fn from(t: Time) -> BrokenDownTime {
3301 BrokenDownTime {
3302 hour: Some(t.hour()),
3303 minute: Some(t.minute()),
3304 second: Some(t.second()),
3305 subsec: Some(t.subsec_nanosecond()),
3306 meridiem: Some(Meridiem::from(t)),
3307 ..BrokenDownTime::default()
3308 }
3309 }
3310}
3311
3312/// A "lazy" implementation of `std::fmt::Display` for `strftime`.
3313///
3314/// Values of this type are created by the `strftime` methods on the various
3315/// datetime types in this crate. For example, [`ZonedDateTime::strftime`].
3316///
3317/// A `Display` captures the information needed from the datetime and waits to
3318/// do the actual formatting when this type's `std::fmt::Display` trait
3319/// implementation is actually used.
3320///
3321/// # Errors and panics
3322///
3323/// This trait implementation configures formatting to use
3324/// [lenient mode](Config::lenient). This avoids panics occurring when using
3325/// APIs like [`Timestamp::strftime`] with unsupported or invalid formatting
3326/// directives. Without lenient mode, whenever formatting would fail, this
3327/// would surface as a panic when converting this display implementation to
3328/// a string.
3329///
3330/// # Example
3331///
3332/// This example shows how to format a zoned datetime using
3333/// [`ZonedDateTime::strftime`]:
3334///
3335/// ```
3336/// use jiff::civil::date;
3337///
3338/// let zdt = date(2024, 7, 15).at(16, 24, 59, 0).in_tz("America/New_York")?;
3339/// let string = zdt.strftime("%a, %-d %b %Y %T %z").to_string();
3340/// assert_eq!(string, "Mon, 15 Jul 2024 16:24:59 -0400");
3341///
3342/// # Ok::<(), Box<dyn std::error::Error>>(())
3343/// ```
3344///
3345/// Or use it directly when writing to something:
3346///
3347/// ```
3348/// use jiff::{civil::date, fmt::strtime};
3349///
3350/// let zdt = date(2024, 7, 15).at(16, 24, 59, 0).in_tz("America/New_York")?;
3351///
3352/// let string = format!("the date is: {}", zdt.strftime("%-m/%-d/%-Y"));
3353/// assert_eq!(string, "the date is: 7/15/2024");
3354///
3355/// # Ok::<(), Box<dyn std::error::Error>>(())
3356/// ```
3357///
3358/// # Example: errors are silently ignored
3359///
3360/// If the formatting string is malformed in some way, then it is silently
3361/// ignored. For example, when using an invalid formatting directive:
3362///
3363/// ```
3364/// use jiff::ZonedDateTime;
3365///
3366/// let zdt = ZonedDateTime::UNIX_EPOCH;
3367/// let string = zdt.strftime("%Y %").to_string();
3368/// assert_eq!(string, "1970 %");
3369/// ```
3370///
3371/// If one wants to surface errors from a formatting string, use a lower
3372/// level API:
3373///
3374/// ```
3375/// use jiff::ZonedDateTime;
3376///
3377/// let zdt = ZonedDateTime::UNIX_EPOCH;
3378/// assert_eq!(
3379/// jiff::fmt::strtime::format("%Y %", &zdt).unwrap_err().to_string(),
3380/// "strftime formatting failed: invalid format string, \
3381/// expected byte after `%`, but found end of format string",
3382/// );
3383/// ```
3384pub struct Display<'f> {
3385 pub(crate) fmt: &'f [u8],
3386 pub(crate) tm: BrokenDownTime,
3387}
3388
3389impl<'f> core::fmt::Display for Display<'f> {
3390 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
3391 use crate::fmt::StdFmtWrite;
3392
3393 self.tm
3394 .format_with_config(
3395 &Config::new().lenient(true),
3396 self.fmt,
3397 &mut StdFmtWrite(f),
3398 )
3399 .map_err(|_| core::fmt::Error)
3400 }
3401}
3402
3403impl<'f> core::fmt::Debug for Display<'f> {
3404 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
3405 f.debug_struct("Display")
3406 .field("fmt", &escape::Bytes(self.fmt))
3407 .field("tm", &self.tm)
3408 .finish()
3409 }
3410}
3411
3412/// A label to disambiguate hours on a 12-hour clock.
3413///
3414/// This can be accessed on a [`BrokenDownTime`] via
3415/// [`BrokenDownTime::meridiem`].
3416#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
3417#[cfg_attr(feature = "defmt", derive(defmt::Format))]
3418pub enum Meridiem {
3419 /// "ante meridiem" or "before midday."
3420 ///
3421 /// Specifically, this describes hours less than 12 on a 24-hour clock.
3422 AM,
3423 /// "post meridiem" or "after midday."
3424 ///
3425 /// Specifically, this describes hours greater than 11 on a 24-hour clock.
3426 PM,
3427}
3428
3429impl Meridiem {
3430 /// Adjusts 12-hour to 24-hour based on meridiem.
3431 fn adjust_hour(self, hour: i8) -> i8 {
3432 match self {
3433 Meridiem::AM => hour % 12,
3434 Meridiem::PM => (hour % 12) + 12,
3435 }
3436 }
3437}
3438
3439impl From<Time> for Meridiem {
3440 fn from(t: Time) -> Meridiem {
3441 if t.hour() < 12 { Meridiem::AM } else { Meridiem::PM }
3442 }
3443}
3444
3445/// These are "extensions" to the standard `strftime` conversion specifiers.
3446///
3447/// This type represents which flags and/or padding were provided with a
3448/// specifier. For example, `%_3d` uses 3 spaces of padding.
3449///
3450/// Currently, this type provides no structured introspection facilities. It
3451/// is exported and available only via implementations of the [`Custom`] trait
3452/// for reasons of semver compatible API evolution. If you have use cases for
3453/// introspecting this type, please open an issue.
3454#[derive(Clone, Debug)]
3455pub struct Extension {
3456 flag: Option<Flag>,
3457 width: Option<u8>,
3458 colons: u8,
3459}
3460
3461impl Extension {
3462 /// Parses an optional directive flag from the beginning of `fmt`. This
3463 /// assumes `fmt` is not empty and guarantees that the return unconsumed
3464 /// slice is also non-empty.
3465 #[cfg_attr(feature = "perf-inline", inline(always))]
3466 fn parse_flag<'i>(
3467 fmt: &'i [u8],
3468 ) -> Result<(Option<Flag>, &'i [u8]), Error> {
3469 let (&byte, tail) = fmt.split_first().unwrap();
3470 let flag = match byte {
3471 b'_' => Flag::PadSpace,
3472 b'0' => Flag::PadZero,
3473 b'-' => Flag::NoPad,
3474 b'^' => Flag::Uppercase,
3475 b'#' => Flag::Swapcase,
3476 _ => return Ok((None, fmt)),
3477 };
3478 if tail.is_empty() {
3479 return Err(Error::from(E::ExpectedDirectiveAfterFlag {
3480 flag: byte,
3481 }));
3482 }
3483 Ok((Some(flag), tail))
3484 }
3485
3486 /// Parses an optional width that comes after a (possibly absent) flag and
3487 /// before the specifier directive itself. And if a width is parsed, the
3488 /// slice returned does not contain it. (If that slice is empty, then an
3489 /// error is returned.)
3490 ///
3491 /// Note that this is also used to parse precision settings for `%f`
3492 /// and `%.f`. In the former case, the width is just re-interpreted as
3493 /// a precision setting. In the latter case, something like `%5.9f` is
3494 /// technically valid, but the `5` is ignored.
3495 #[cfg_attr(feature = "perf-inline", inline(always))]
3496 fn parse_width<'i>(
3497 fmt: &'i [u8],
3498 ) -> Result<(Option<u8>, &'i [u8]), Error> {
3499 let mut digits = 0;
3500 while digits < fmt.len() && fmt[digits].is_ascii_digit() {
3501 digits += 1;
3502 }
3503 if digits == 0 {
3504 return Ok((None, fmt));
3505 }
3506 let (digits, fmt) = fmt.split_at(digits);
3507 let width = util::parse::i64(digits).context(E::FailedWidth)?;
3508 let width = u8::try_from(width).map_err(|_| E::RangeWidth)?;
3509 if fmt.is_empty() {
3510 return Err(Error::from(E::ExpectedDirectiveAfterWidth));
3511 }
3512 Ok((Some(width), fmt))
3513 }
3514
3515 /// Parses an optional number of colons.
3516 ///
3517 /// This is meant to be used immediately before the conversion specifier
3518 /// (after the flag and width has been parsed).
3519 ///
3520 /// This supports parsing up to 3 colons. The colons are used in some cases
3521 /// for alternate specifiers. e.g., `%:Q` or `%:::z`.
3522 #[cfg_attr(feature = "perf-inline", inline(always))]
3523 fn parse_colons<'i>(fmt: &'i [u8]) -> Result<(u8, &'i [u8]), Error> {
3524 let mut colons = 0;
3525 while colons < 3 && colons < fmt.len() && fmt[colons] == b':' {
3526 colons += 1;
3527 }
3528 let fmt = &fmt[usize::from(colons)..];
3529 if colons > 0 && fmt.is_empty() {
3530 return Err(Error::from(E::ExpectedDirectiveAfterColons));
3531 }
3532 Ok((u8::try_from(colons).unwrap(), fmt))
3533 }
3534}
3535
3536/// The different flags one can set. They are mutually exclusive.
3537#[derive(Clone, Copy, Debug)]
3538enum Flag {
3539 PadSpace,
3540 PadZero,
3541 NoPad,
3542 Uppercase,
3543 Swapcase,
3544}
3545
3546/// Returns the "full" weekday name.
3547#[cfg_attr(feature = "perf-inline", inline(always))]
3548fn weekday_name_full(wd: Weekday) -> &'static str {
3549 match wd {
3550 Weekday::Sunday => "Sunday",
3551 Weekday::Monday => "Monday",
3552 Weekday::Tuesday => "Tuesday",
3553 Weekday::Wednesday => "Wednesday",
3554 Weekday::Thursday => "Thursday",
3555 Weekday::Friday => "Friday",
3556 Weekday::Saturday => "Saturday",
3557 }
3558}
3559
3560/// Returns an abbreviated weekday name.
3561#[cfg_attr(feature = "perf-inline", inline(always))]
3562fn weekday_name_abbrev(wd: Weekday) -> &'static str {
3563 match wd {
3564 Weekday::Sunday => "Sun",
3565 Weekday::Monday => "Mon",
3566 Weekday::Tuesday => "Tue",
3567 Weekday::Wednesday => "Wed",
3568 Weekday::Thursday => "Thu",
3569 Weekday::Friday => "Fri",
3570 Weekday::Saturday => "Sat",
3571 }
3572}
3573
3574/// Returns the "full" month name.
3575///
3576/// # Panics
3577///
3578/// When the given value is not in the range `1..=12`.
3579#[cfg_attr(feature = "perf-inline", inline(always))]
3580fn month_name_full(month: i8) -> &'static str {
3581 match month {
3582 1 => "January",
3583 2 => "February",
3584 3 => "March",
3585 4 => "April",
3586 5 => "May",
3587 6 => "June",
3588 7 => "July",
3589 8 => "August",
3590 9 => "September",
3591 10 => "October",
3592 11 => "November",
3593 12 => "December",
3594 unk => unreachable!("invalid month {unk}"),
3595 }
3596}
3597
3598/// Returns the abbreviated month name.
3599///
3600/// # Panics
3601///
3602/// When the given value is not in the range `1..=12`.
3603#[cfg_attr(feature = "perf-inline", inline(always))]
3604fn month_name_abbrev(month: i8) -> &'static str {
3605 match month {
3606 1 => "Jan",
3607 2 => "Feb",
3608 3 => "Mar",
3609 4 => "Apr",
3610 5 => "May",
3611 6 => "Jun",
3612 7 => "Jul",
3613 8 => "Aug",
3614 9 => "Sep",
3615 10 => "Oct",
3616 11 => "Nov",
3617 12 => "Dec",
3618 unk => unreachable!("invalid month {unk}"),
3619 }
3620}
3621
3622#[cfg(test)]
3623mod tests {
3624 use super::*;
3625
3626 // See: https://github.com/BurntSushi/jiff/issues/62
3627 #[test]
3628 fn parse_non_delimited() {
3629 insta::assert_snapshot!(
3630 Timestamp::strptime("%Y%m%d-%H%M%S%z", "20240730-005625+0400").unwrap(),
3631 @"2024-07-29T20:56:25Z",
3632 );
3633 insta::assert_snapshot!(
3634 ZonedDateTime::strptime("%Y%m%d-%H%M%S%z", "20240730-005625+0400")
3635 .unwrap(),
3636 @"2024-07-30T00:56:25+04:00[+04:00]",
3637 );
3638 }
3639
3640 // Regression test for format strings with non-ASCII in them.
3641 //
3642 // We initially didn't support non-ASCII because I had thought it wouldn't
3643 // be used. i.e., If someone wanted to do something with non-ASCII, then
3644 // I thought they'd want to be using something more sophisticated that took
3645 // locale into account. But apparently not.
3646 //
3647 // See: https://github.com/BurntSushi/jiff/issues/155
3648 #[test]
3649 fn ok_non_ascii() {
3650 let fmt = "%Y年%m月%d日,%H时%M分%S秒";
3651 let dt = crate::civil::date(2022, 2, 4).at(3, 58, 59, 0);
3652 insta::assert_snapshot!(
3653 dt.strftime(fmt),
3654 @"2022年02月04日,03时58分59秒",
3655 );
3656 insta::assert_debug_snapshot!(
3657 DateTime::strptime(fmt, "2022年02月04日,03时58分59秒").unwrap(),
3658 @"2022-02-04T03:58:59",
3659 );
3660 }
3661
3662 // Regression tests for #718.
3663 #[cfg(feature = "alloc")]
3664 #[test]
3665 fn parse_zoned_datetime_out_of_range() {
3666 if crate::tz::db().is_definitively_empty() {
3667 return;
3668 }
3669
3670 insta::assert_snapshot!(
3671 ZonedDateTime::strptime(
3672 "%F %T %z %Q",
3673 "9999-12-31 23:59:59 +0900 Asia/Tokyo",
3674 ).unwrap_err(),
3675 @"error converting datetime to instant in time zone Asia/Tokyo: \
3676 converting datetime with time zone offset `+09` to timestamp \
3677 overflowed: parameter 'Unix timestamp seconds' is not \
3678 in the required range of -377705023201..=253402207200",
3679 );
3680 insta::assert_snapshot!(
3681 ZonedDateTime::strptime(
3682 "%F %T %::z %Q",
3683 "-9999-01-01 00:00:00 -04:56:02 America/New_York",
3684 ).unwrap_err(),
3685 @"error converting datetime to instant in time zone \
3686 America/New_York: converting datetime with time zone offset \
3687 `-04:56:02` to timestamp overflowed: parameter 'Unix timestamp \
3688 seconds' is not in the required range of \
3689 -377705023201..=253402207200",
3690 );
3691 }
3692
3693 // `BrokenDownTime::from(&ZonedDateTime)` borrows the IANA identifier from
3694 // the time zone instead of copying it. Clearing it must still stick.
3695 #[cfg(feature = "alloc")]
3696 #[test]
3697 fn iana_time_zone_from_zoned() {
3698 if crate::tz::db().is_definitively_empty() {
3699 return;
3700 }
3701
3702 let zdt = crate::civil::date(2024, 7, 15)
3703 .at(16, 24, 59, 0)
3704 .in_tz("America/New_York")
3705 .unwrap();
3706 let mut tm = BrokenDownTime::from(&zdt);
3707 assert_eq!(tm.iana_time_zone(), Some("America/New_York"));
3708 insta::assert_snapshot!(
3709 tm.to_string("%Q %Z").unwrap(),
3710 @"America/New_York EDT",
3711 );
3712
3713 tm.set_iana_time_zone(None);
3714 assert_eq!(tm.iana_time_zone(), None);
3715 insta::assert_snapshot!(tm.to_string("%Q %Z").unwrap(), @"-0400 EDT");
3716
3717 tm.set_iana_time_zone(Some("Australia/Tasmania".into()));
3718 assert_eq!(tm.iana_time_zone(), Some("Australia/Tasmania"));
3719 }
3720}