jiff/fmt/temporal/pieces.rs
1use crate::{
2 Timestamp, ZonedDateTime,
3 civil::{Date, DateTime, Time},
4 error::Error,
5 tz::{Offset, TimeZone, TimeZoneDatabase},
6 util::borrow::StringCow,
7};
8
9/// A low level representation of a parsed Temporal ISO 8601 datetime string.
10///
11/// Most users should not need to use or care about this type. Its purpose is
12/// to represent the individual components of a datetime string for more
13/// flexible parsing when use cases call for it.
14///
15/// One can parse into `Pieces` via [`Pieces::parse`]. Its date, time
16/// (optional), offset (optional) and time zone annotation (optional) can be
17/// queried independently. Each component corresponds to the following in a
18/// datetime string:
19///
20/// ```text
21/// {date}T{time}{offset}[{time-zone-annotation}]
22/// ```
23///
24/// For example:
25///
26/// ```text
27/// 2025-01-03T19:54-05[America/New_York]
28/// ```
29///
30/// A date is the only required component.
31///
32/// A `Pieces` can also be constructed from structured values via its `From`
33/// trait implementations. The `From` trait has the following implementations
34/// available:
35///
36/// * `From<Date>` creates a `Pieces` with just a civil [`Date`]. All other
37/// components are left empty.
38/// * `From<DateTime>` creates a `Pieces` with a civil [`Date`] and [`Time`].
39/// The offset and time zone annotation are left empty.
40/// * `From<Timestamp>` creates a `Pieces` from a [`Timestamp`] using
41/// a Zulu offset. This signifies that the precise instant is known, but the
42/// local time's offset from UTC is unknown. The [`Date`] and [`Time`] are
43/// determined via `Offset::UTC.to_datetime(timestamp)`. The time zone
44/// annotation is left empty.
45/// * `From<(Timestamp, Offset)>` creates a `Pieces` from a [`Timestamp`] and
46/// an [`Offset`]. The [`Date`] and [`Time`] are determined via
47/// `offset.to_datetime(timestamp)`. The time zone annotation is left empty.
48/// * `From<&ZonedDateTime>` creates a `Pieces` from a [`ZonedDateTime`]. This
49/// populates all fields of a `Pieces`.
50///
51/// A `Pieces` can be converted to a Temporal ISO 8601 string via its `Display`
52/// trait implementation.
53///
54/// # Example: distinguishing between `Z`, `+00:00` and `-00:00`
55///
56/// With `Pieces`, it's possible to parse a datetime string and inspect the
57/// "type" of its offset when it is zero. This makes use of the
58/// [`PiecesOffset`] and [`PiecesNumericOffset`] auxiliary types.
59///
60/// ```
61/// use jiff::{
62/// fmt::temporal::{Pieces, PiecesNumericOffset, PiecesOffset},
63/// tz::Offset,
64/// };
65///
66/// let pieces = Pieces::parse("1970-01-01T00:00:00Z")?;
67/// let off = pieces.offset().unwrap();
68/// // Parsed as Zulu.
69/// assert_eq!(off, PiecesOffset::Zulu);
70/// // Gets converted from Zulu to UTC, i.e., just zero.
71/// assert_eq!(off.to_numeric_offset(), Offset::UTC);
72///
73/// let pieces = Pieces::parse("1970-01-01T00:00:00-00:00")?;
74/// let off = pieces.offset().unwrap();
75/// // Parsed as a negative zero.
76/// assert_eq!(off, PiecesOffset::from(
77/// PiecesNumericOffset::from(Offset::UTC).with_negative_zero(),
78/// ));
79/// // Gets converted from -00:00 to UTC, i.e., just zero.
80/// assert_eq!(off.to_numeric_offset(), Offset::UTC);
81///
82/// let pieces = Pieces::parse("1970-01-01T00:00:00+00:00")?;
83/// let off = pieces.offset().unwrap();
84/// // Parsed as a positive zero.
85/// assert_eq!(off, PiecesOffset::from(
86/// PiecesNumericOffset::from(Offset::UTC),
87/// ));
88/// // Gets converted from -00:00 to UTC, i.e., just zero.
89/// assert_eq!(off.to_numeric_offset(), Offset::UTC);
90///
91/// # Ok::<(), Box<dyn std::error::Error>>(())
92/// ```
93///
94/// It's rare to need to care about these differences, but the above example
95/// demonstrates that `Pieces` doesn't try to do any automatic translation for
96/// you.
97///
98/// # Example: it is very easy to misuse `Pieces`
99///
100/// This example shows how easily you can shoot yourself in the foot with
101/// `Pieces`:
102///
103/// ```
104/// use jiff::{fmt::temporal::{Pieces, TimeZoneAnnotation}, tz};
105///
106/// let mut pieces = Pieces::parse("2025-01-03T07:55+02[Africa/Cairo]")?;
107/// pieces = pieces.with_offset(tz::offset(-10));
108/// // This is nonsense because the offset isn't compatible with the time zone!
109/// // Moreover, the actual instant that this timestamp represents has changed.
110/// assert_eq!(pieces.to_string(), "2025-01-03T07:55:00-10:00[Africa/Cairo]");
111///
112/// # Ok::<(), Box<dyn std::error::Error>>(())
113/// ```
114///
115/// In the above example, we take a parsed `Pieces`, change its offset and
116/// then format it back into a string. There are no speed bumps or errors.
117/// A `Pieces` will just blindly follow your instruction, even if it produces
118/// a nonsense result. Nonsense results are still parsable back into `Pieces`:
119///
120/// ```
121/// use jiff::{civil, fmt::temporal::Pieces, tz::{TimeZone, offset}};
122///
123/// let pieces = Pieces::parse("2025-01-03T07:55:00-10:00[Africa/Cairo]")?;
124/// assert_eq!(pieces.date(), civil::date(2025, 1, 3));
125/// assert_eq!(pieces.time(), Some(civil::time(7, 55, 0, 0)));
126/// assert_eq!(pieces.to_numeric_offset(), Some(offset(-10)));
127/// assert_eq!(pieces.to_time_zone()?, Some(TimeZone::get("Africa/Cairo")?));
128///
129/// # Ok::<(), Box<dyn std::error::Error>>(())
130/// ```
131///
132/// This exemplifies that `Pieces` is a mostly "dumb" type that passes
133/// through the data it contains, even if it doesn't make sense.
134///
135/// # Case study: how to parse `2025-01-03T17:28-05` into `ZonedDateTime`
136///
137/// One thing in particular that `Pieces` enables callers to do is side-step
138/// some of the stricter requirements placed on the higher level parsing
139/// functions (such as `ZonedDateTime`'s `FromStr` trait implementation). For
140/// example, parsing a datetime string into a `ZonedDateTime` _requires_ that
141/// the string contain a time zone annotation. Namely, parsing
142/// `2025-01-03T17:28-05` into a `ZonedDateTime` will fail:
143///
144/// ```
145/// use jiff::ZonedDateTime;
146///
147/// assert_eq!(
148/// "2025-01-03T17:28-05"
149/// .parse::<ZonedDateTime>()
150/// .unwrap_err()
151/// .to_string(),
152/// "failed to find time zone annotation in square brackets, \
153/// which is required for parsing a zoned datetime",
154/// );
155/// ```
156///
157/// The above fails because an RFC 3339 timestamp only contains an offset, not
158/// a time zone, and thus the resulting `ZonedDateTime` could never do time
159/// zone aware arithmetic.
160///
161/// However, in some cases, you might want to bypass these protections and
162/// creat a `ZonedDateTime` value with a fixed offset time zone anyway. For
163/// example, perhaps your use cases don't need time zone aware arithmetic, but
164/// want to preserve the offset anyway. This can be accomplished with `Pieces`:
165///
166/// ```
167/// use jiff::{fmt::temporal::Pieces, tz::TimeZone};
168///
169/// let pieces = Pieces::parse("2025-01-03T17:28-05")?;
170/// let time = pieces.time().unwrap_or_else(jiff::civil::Time::midnight);
171/// let dt = pieces.date().to_datetime(time);
172/// let Some(offset) = pieces.to_numeric_offset() else {
173/// let msg = format!(
174/// "datetime string has no offset, \
175/// and thus cannot be parsed into an instant",
176/// );
177/// return Err(msg.into());
178/// };
179/// let zdt = TimeZone::fixed(offset).to_zoned_datetime(dt)?;
180/// assert_eq!(zdt.to_string(), "2025-01-03T17:28:00-05:00[-05:00]");
181///
182/// # Ok::<(), Box<dyn std::error::Error>>(())
183/// ```
184///
185/// One problem with the above code snippet is that it completely ignores if
186/// a time zone annotation is present. If it is, it probably makes sense to use
187/// it, but "fall back" to a fixed offset time zone if it isn't (which the
188/// higher level `ZonedDateTime` parsing function won't do for you):
189///
190/// ```
191/// use jiff::{fmt::temporal::Pieces, tz::TimeZone};
192///
193/// let timestamp = "2025-01-02T15:13-05";
194///
195/// let pieces = Pieces::parse(timestamp)?;
196/// let time = pieces.time().unwrap_or_else(jiff::civil::Time::midnight);
197/// let dt = pieces.date().to_datetime(time);
198/// let tz = match pieces.to_time_zone()? {
199/// Some(tz) => tz,
200/// None => {
201/// let Some(offset) = pieces.to_numeric_offset() else {
202/// let msg = format!(
203/// "timestamp `{timestamp}` has no time zone \
204/// or offset, and thus cannot be parsed into \
205/// an instant",
206/// );
207/// return Err(msg.into());
208/// };
209/// TimeZone::fixed(offset)
210/// }
211/// };
212/// // We don't bother with offset conflict resolution. And note that
213/// // this uses automatic "compatible" disambiguation in the case of
214/// // discontinuities. Of course, this is all moot if `TimeZone` is
215/// // fixed. The above code handles the case where it isn't!
216/// let zdt = tz.to_zoned_datetime(dt)?;
217/// assert_eq!(zdt.to_string(), "2025-01-02T15:13:00-05:00[-05:00]");
218///
219/// # Ok::<(), Box<dyn std::error::Error>>(())
220/// ```
221///
222/// This is mostly the same as above, but if an annotation is present, we use
223/// a `TimeZone` derived from that over the offset present.
224///
225/// However, this still doesn't quite capture what happens when parsing into a
226/// `ZonedDateTime` value. In particular, parsing into a `ZonedDateTime` is
227/// _also_ doing offset conflict resolution for you. An offset conflict occurs
228/// when there is a mismatch between the offset in an RFC 3339 timestamp and
229/// the time zone in an RFC 9557 time zone annotation.
230///
231/// For example, `2024-06-14T17:30-05[America/New_York]` has a mismatch
232/// since the date is in daylight saving time, but the offset, `-05`, is the
233/// offset for standard time in `America/New_York`. If this datetime were
234/// fed to the above code, then the `-05` offset would be completely ignored
235/// and `America/New_York` would resolve the datetime based on its rules. In
236/// this case, you'd get `2024-06-14T17:30-04`, which is a different instant
237/// than the original datetime!
238///
239/// You can either implement your own conflict resolution or use
240/// [`tz::OffsetConflict`](crate::tz::OffsetConflict) to do it for you.
241///
242/// ```
243/// use jiff::{fmt::temporal::Pieces, tz::{OffsetConflict, TimeZone}};
244///
245/// let timestamp = "2024-06-14T17:30-05[America/New_York]";
246/// // The default for conflict resolution when parsing into a `ZonedDateTime`
247/// // is actually `Reject`, but we use `AlwaysOffset` here to show a different
248/// // strategy. You'll want to pick the conflict resolution that suits your
249/// // needs. The `Reject` strategy is what you should pick if you aren't sure.
250/// let conflict_resolution = OffsetConflict::AlwaysOffset;
251///
252/// let pieces = Pieces::parse(timestamp)?;
253/// let time = pieces.time().unwrap_or_else(jiff::civil::Time::midnight);
254/// let dt = pieces.date().to_datetime(time);
255/// let ambiguous_zdt = match pieces.to_time_zone()? {
256/// Some(tz) => match pieces.to_numeric_offset() {
257/// None => tz.into_ambiguous_zoned_datetime(dt),
258/// Some(offset) => conflict_resolution.resolve(dt, offset, tz)?,
259/// },
260/// None => {
261/// let Some(offset) = pieces.to_numeric_offset() else {
262/// let msg = format!(
263/// "timestamp `{timestamp}` has no time zone \
264/// or offset, and thus cannot be parsed into \
265/// an instant",
266/// );
267/// return Err(msg.into());
268/// };
269/// // Won't even be ambiguous, but gets us the same
270/// // type as the branch above.
271/// TimeZone::fixed(offset).into_ambiguous_zoned_datetime(dt)
272/// }
273/// };
274/// // We do compatible disambiguation here like we do in the previous
275/// // examples, but you could choose any strategy. As with offset conflict
276/// // resolution, if you aren't sure what to pick, a safe choice here would
277/// // be `ambiguous_zdt.unambiguous()`, which will return an error if the
278/// // datetime is ambiguous in any way. Then, if you ever hit an error, you
279/// // can examine the case to see if it should be handled in a different way.
280/// let zdt = ambiguous_zdt.compatible()?;
281/// // Notice that we now have a different civil time and offset, but the
282/// // instant it corresponds to is the same as the one we started with.
283/// assert_eq!(zdt.to_string(), "2024-06-14T18:30:00-04:00[America/New_York]");
284///
285/// # Ok::<(), Box<dyn std::error::Error>>(())
286/// ```
287///
288/// The above has effectively completely rebuilt the higher level
289/// `ZonedDateTime` parsing routine, but with a fallback to a fixed time zone
290/// when a time zone annotation is not present.
291///
292/// # Case study: inferring the time zone of RFC 3339 timestamps
293///
294/// As [one real world use case details][infer-time-zone], it might be
295/// desirable to try and infer the time zone of RFC 3339 timestamps with
296/// varying offsets. This might be applicable when:
297///
298/// * You have out-of-band information, possibly contextual, that indicates
299/// the timestamps have to come from a fixed set of time zones.
300/// * The time zones have different standard offsets.
301/// * You have a specific desire or need to use a [`ZonedDateTime`] value for
302/// its ergonomics and time zone aware handling. After all, in this case, you
303/// believe the timestamps to actually be generated from a specific time zone,
304/// but the interchange format doesn't support carrying that information. Or
305/// the source data simply omits it.
306///
307/// In other words, you might be trying to make the best of a bad situation.
308///
309/// A `Pieces` can help you accomplish this because it gives you access to each
310/// component of a parsed datetime, and thus lets you implement arbitrary logic
311/// for how to translate that into a `ZonedDateTime`. In this case, there is
312/// contextual information that Jiff can't possibly know about.
313///
314/// The general approach we take here is to make use of
315/// [`tz::OffsetConflict`](crate::tz::OffsetConflict) to query whether a
316/// timestamp has a fixed offset compatible with a particular time zone. And if
317/// so, we can _probably_ assume it comes from that time zone. One hitch is
318/// that it's possible for the timestamp to be valid for multiple time zones,
319/// so we check that as well.
320///
321/// In the use case linked above, we have fixed offset timestamps from
322/// `America/Chicago` and `America/New_York`. So let's try implementing the
323/// above strategy. Note that we assume our inputs are RFC 3339 fixed offset
324/// timestamps and error otherwise. This is just to keep things simple. To
325/// handle data that is more varied, see the previous case study where we
326/// respect a time zone annotation if it's present, and fall back to a fixed
327/// offset time zone if it isn't.
328///
329/// ```
330/// use jiff::{
331/// ZonedDateTime,
332/// fmt::temporal::Pieces,
333/// tz::{OffsetConflict, TimeZone},
334/// };
335///
336/// // The time zones we're allowed to choose from.
337/// let tzs = &[
338/// TimeZone::get("America/New_York")?,
339/// TimeZone::get("America/Chicago")?,
340/// ];
341///
342/// // Here's our data that lacks time zones. The task is to assign a time zone
343/// // from `tzs` to each below and convert it to a `ZonedDateTime`. If we fail
344/// // on any one, then we substitute `None`.
345/// let data = &[
346/// "2024-01-13T10:33-05",
347/// "2024-01-25T12:15-06",
348/// "2024-03-10T02:30-05",
349/// "2024-06-08T14:01-05",
350/// "2024-06-12T11:46-04",
351/// "2024-11-03T01:30-05",
352/// ];
353/// // Our answers.
354/// let mut zdts: Vec<Option<ZonedDateTime>> = vec![];
355/// for string in data {
356/// // Parse and gather up the data that we can from the input.
357/// // In this case, that's a civil datetime and an offset from UTC.
358/// let pieces = Pieces::parse(string)?;
359/// let time = pieces.time().unwrap_or_else(jiff::civil::Time::midnight);
360/// let dt = pieces.date().to_datetime(time);
361/// let Some(offset) = pieces.to_numeric_offset() else {
362/// // A robust implementation should use a TZ annotation if present.
363/// return Err("missing offset".into());
364/// };
365/// // Now collect all time zones that are valid for this timestamp.
366/// let mut candidates = vec![];
367/// for tz in tzs {
368/// let result = OffsetConflict::Reject.resolve(dt, offset, tz.clone());
369/// // The parsed offset isn't valid for this time zone, so reject it.
370/// let Ok(ambiguous_zdt) = result else { continue };
371/// // This can never fail because we used the "reject" conflict
372/// // resolution strategy. It will never return an ambiguous
373/// // `ZonedDateTime` since we always have a valid offset that does
374/// // disambiguation for us.
375/// let zdt = ambiguous_zdt.unambiguous().unwrap();
376/// candidates.push(zdt);
377/// }
378/// if candidates.len() == 1 {
379/// zdts.push(Some(candidates.pop().unwrap()));
380/// } else {
381/// zdts.push(None);
382/// }
383/// }
384/// assert_eq!(zdts, vec![
385/// Some("2024-01-13T10:33-05[America/New_York]".parse()?),
386/// Some("2024-01-25T12:15-06[America/Chicago]".parse()?),
387/// // Failed because the clock time falls in a gap in the
388/// // transition to daylight saving time, and it could be
389/// // valid for either America/New_York or America/Chicago.
390/// None,
391/// Some("2024-06-08T14:01-05[America/Chicago]".parse()?),
392/// Some("2024-06-12T11:46-04[America/New_York]".parse()?),
393/// // Failed because the clock time falls in a fold in the
394/// // transition out of daylight saving time, and it could be
395/// // valid for either America/New_York or America/Chicago.
396/// None,
397/// ]);
398///
399/// # Ok::<(), Box<dyn std::error::Error>>(())
400/// ```
401///
402/// The one hitch here is that if the time zones are close to each
403/// geographically and both have daylight saving time, then there are some
404/// RFC 3339 timestamps that are truly ambiguous. For example,
405/// `2024-11-03T01:30-05` is perfectly valid for both `America/New_York` and
406/// `America/Chicago`. In this case, there is no way to tell which time zone
407/// the timestamp belongs to. It might be reasonable to return an error in
408/// this case or omit the timestamp. It depends on what you need to do.
409///
410/// With more effort, it would also be possible to optimize the above routine
411/// by utilizing [`TimeZone::preceding`] and [`TimeZone::following`] to get
412/// the exact boundaries of each time zone transition. Then you could use an
413/// offset lookup table for each range to determine the appropriate time zone.
414///
415/// [infer-time-zone]: https://github.com/BurntSushi/jiff/discussions/181#discussioncomment-11729435
416#[derive(Clone, Debug, Eq, Hash, PartialEq)]
417#[cfg_attr(feature = "defmt", derive(defmt::Format))]
418pub struct Pieces<'n> {
419 date: Date,
420 time: Option<Time>,
421 offset: Option<PiecesOffset>,
422 time_zone_annotation: Option<TimeZoneAnnotation<'n>>,
423}
424
425impl<'n> Pieces<'n> {
426 /// Parses a Temporal ISO 8601 datetime string into a `Pieces`.
427 ///
428 /// This is a convenience routine for
429 /// [`DateTimeParser::parses_pieces`](crate::fmt::temporal::DateTimeParser::parse_pieces).
430 ///
431 /// Note that the `Pieces` returned is parameterized by the lifetime of
432 /// `input`. This is because it might borrow a sub-slice of `input` for
433 /// a time zone annotation name. For example,
434 /// `America/Whitehorse` in `2025-01-03T16:42-07[America/Whitehorse]`.
435 ///
436 /// # Example
437 ///
438 /// ```
439 /// use jiff::{civil, fmt::temporal::Pieces, tz::TimeZone};
440 ///
441 /// let pieces = Pieces::parse("2025-01-03T16:42[America/Whitehorse]")?;
442 /// assert_eq!(pieces.date(), civil::date(2025, 1, 3));
443 /// assert_eq!(pieces.time(), Some(civil::time(16, 42, 0, 0)));
444 /// assert_eq!(pieces.to_numeric_offset(), None);
445 /// assert_eq!(
446 /// pieces.to_time_zone()?,
447 /// Some(TimeZone::get("America/Whitehorse")?),
448 /// );
449 ///
450 /// # Ok::<(), Box<dyn std::error::Error>>(())
451 /// ```
452 #[inline]
453 pub fn parse<I: ?Sized + AsRef<[u8]> + 'n>(
454 input: &'n I,
455 ) -> Result<Pieces<'n>, Error> {
456 let input = input.as_ref();
457 super::DEFAULT_DATETIME_PARSER.parse_pieces(input)
458 }
459
460 /// Returns the civil date in this `Pieces`.
461 ///
462 /// Note that every `Pieces` value is guaranteed to have a `Date`.
463 ///
464 /// # Example
465 ///
466 /// ```
467 /// use jiff::{civil, fmt::temporal::Pieces};
468 ///
469 /// let pieces = Pieces::parse("2025-01-03")?;
470 /// assert_eq!(pieces.date(), civil::date(2025, 1, 3));
471 ///
472 /// # Ok::<(), Box<dyn std::error::Error>>(())
473 /// ```
474 #[inline]
475 pub fn date(&self) -> Date {
476 self.date
477 }
478
479 /// Returns the civil time in this `Pieces`.
480 ///
481 /// The time component is optional. In
482 /// [`DateTimeParser`](crate::fmt::temporal::DateTimeParser), parsing
483 /// into types that require a time (like [`DateTime`]) when a time is
484 /// missing automatically set the time to midnight. (Or, more precisely,
485 /// the first instant of the day.)
486 ///
487 /// # Example
488 ///
489 /// ```
490 /// use jiff::{ZonedDateTime, civil, fmt::temporal::Pieces};
491 ///
492 /// let pieces = Pieces::parse("2025-01-03T14:49:01")?;
493 /// assert_eq!(pieces.date(), civil::date(2025, 1, 3));
494 /// assert_eq!(pieces.time(), Some(civil::time(14, 49, 1, 0)));
495 ///
496 /// // tricksy tricksy, the first instant of 2015-10-18 in Sao Paulo is
497 /// // not midnight!
498 /// let pieces = Pieces::parse("2015-10-18[America/Sao_Paulo]")?;
499 /// // Parsing into pieces just gives us the component parts, so no time:
500 /// assert_eq!(pieces.time(), None);
501 ///
502 /// // But if this uses higher level routines to parse into a
503 /// // `ZonedDateTime`, then we can see that the missing time implies the
504 /// // first instant of the day:
505 /// let zdt: ZonedDateTime = "2015-10-18[America/Sao_Paulo]".parse()?;
506 /// assert_eq!(zdt.time(), jiff::civil::time(1, 0, 0, 0));
507 ///
508 /// # Ok::<(), Box<dyn std::error::Error>>(())
509 /// ```
510 #[inline]
511 pub fn time(&self) -> Option<Time> {
512 self.time
513 }
514
515 /// Returns the offset in this `Pieces`.
516 ///
517 /// The offset returned can be infallibly converted to a numeric offset,
518 /// i.e., [`Offset`]. But it also includes extra data to indicate whether
519 /// a `Z` or a `-00:00` was parsed. (Neither of which are representable by
520 /// an `Offset`, which doesn't distinguish between Zulu and UTC and doesn't
521 /// represent negative and positive zero differently.)
522 ///
523 /// # Example
524 ///
525 /// This example shows how different flavors of `Offset::UTC` can be parsed
526 /// and inspected.
527 ///
528 /// ```
529 /// use jiff::{
530 /// fmt::temporal::{Pieces, PiecesNumericOffset, PiecesOffset},
531 /// tz::Offset,
532 /// };
533 ///
534 /// let pieces = Pieces::parse("1970-01-01T00:00:00Z")?;
535 /// let off = pieces.offset().unwrap();
536 /// // Parsed as Zulu.
537 /// assert_eq!(off, PiecesOffset::Zulu);
538 /// // Gets converted from Zulu to UTC, i.e., just zero.
539 /// assert_eq!(off.to_numeric_offset(), Offset::UTC);
540 ///
541 /// let pieces = Pieces::parse("1970-01-01T00:00:00-00:00")?;
542 /// let off = pieces.offset().unwrap();
543 /// // Parsed as a negative zero.
544 /// assert_eq!(off, PiecesOffset::from(
545 /// PiecesNumericOffset::from(Offset::UTC).with_negative_zero(),
546 /// ));
547 /// // Gets converted from -00:00 to UTC, i.e., just zero.
548 /// assert_eq!(off.to_numeric_offset(), Offset::UTC);
549 ///
550 /// let pieces = Pieces::parse("1970-01-01T00:00:00+00:00")?;
551 /// let off = pieces.offset().unwrap();
552 /// // Parsed as a positive zero.
553 /// assert_eq!(off, PiecesOffset::from(
554 /// PiecesNumericOffset::from(Offset::UTC),
555 /// ));
556 /// // Gets converted from -00:00 to UTC, i.e., just zero.
557 /// assert_eq!(off.to_numeric_offset(), Offset::UTC);
558 ///
559 /// # Ok::<(), Box<dyn std::error::Error>>(())
560 /// ```
561 #[inline]
562 pub fn offset(&self) -> Option<PiecesOffset> {
563 self.offset
564 }
565
566 /// Returns the time zone annotation in this `Pieces`.
567 ///
568 /// A time zone annotation is optional. The higher level
569 /// [`DateTimeParser`](crate::fmt::temporal::DateTimeParser)
570 /// requires a time zone annotation when parsing into a [`ZonedDateTime`].
571 ///
572 /// A time zone annotation is either an offset, or more commonly, an IANA
573 /// time zone identifier.
574 ///
575 /// # Example
576 ///
577 /// ```
578 /// use jiff::{fmt::temporal::{Pieces, TimeZoneAnnotation}, tz::offset};
579 ///
580 /// // A time zone annotation from a name:
581 /// let pieces = Pieces::parse("2025-01-02T16:47-05[America/New_York]")?;
582 /// assert_eq!(
583 /// pieces.time_zone_annotation().unwrap(),
584 /// &TimeZoneAnnotation::from("America/New_York"),
585 /// );
586 ///
587 /// // A time zone annotation from an offset:
588 /// let pieces = Pieces::parse("2025-01-02T16:47-05[-05:00]")?;
589 /// assert_eq!(
590 /// pieces.time_zone_annotation().unwrap(),
591 /// &TimeZoneAnnotation::from(offset(-5)),
592 /// );
593 ///
594 /// # Ok::<(), Box<dyn std::error::Error>>(())
595 /// ```
596 #[inline]
597 pub fn time_zone_annotation(&self) -> Option<&TimeZoneAnnotation<'n>> {
598 self.time_zone_annotation.as_ref()
599 }
600
601 /// A convenience routine for converting an offset on this `Pieces`,
602 /// if present, to a numeric [`Offset`].
603 ///
604 /// This collapses the offsets `Z`, `-00:00` and `+00:00` all to
605 /// [`Offset::UTC`]. If you need to distinguish between them, then use
606 /// [`Pieces::offset`].
607 ///
608 /// # Example
609 ///
610 /// This example shows how `Z`, `-00:00` and `+00:00` all map to the same
611 /// [`Offset`] value:
612 ///
613 /// ```
614 /// use jiff::{fmt::temporal::Pieces, tz::Offset};
615 ///
616 /// let pieces = Pieces::parse("1970-01-01T00:00:00Z")?;
617 /// assert_eq!(pieces.to_numeric_offset(), Some(Offset::UTC));
618 ///
619 /// let pieces = Pieces::parse("1970-01-01T00:00:00-00:00")?;
620 /// assert_eq!(pieces.to_numeric_offset(), Some(Offset::UTC));
621 ///
622 /// let pieces = Pieces::parse("1970-01-01T00:00:00+00:00")?;
623 /// assert_eq!(pieces.to_numeric_offset(), Some(Offset::UTC));
624 ///
625 /// # Ok::<(), Box<dyn std::error::Error>>(())
626 /// ```
627 #[inline]
628 pub fn to_numeric_offset(&self) -> Option<Offset> {
629 self.offset().map(|poffset| poffset.to_numeric_offset())
630 }
631
632 /// A convenience routine for converting a time zone annotation, if
633 /// present, into a [`TimeZone`].
634 ///
635 /// If no annotation is on this `Pieces`, then this returns `Ok(None)`.
636 ///
637 /// This may return an error if the time zone annotation is a name and it
638 /// couldn't be found in Jiff's global time zone database.
639 ///
640 /// # Example
641 ///
642 /// ```
643 /// use jiff::{fmt::temporal::Pieces, tz::{TimeZone, offset}};
644 ///
645 /// // No time zone annotations means you get `Ok(None)`:
646 /// let pieces = Pieces::parse("2025-01-03T17:13-05")?;
647 /// assert_eq!(pieces.to_time_zone()?, None);
648 ///
649 /// // An offset time zone annotation gets you a fixed offset `TimeZone`:
650 /// let pieces = Pieces::parse("2025-01-03T17:13-05[-05]")?;
651 /// assert_eq!(pieces.to_time_zone()?, Some(TimeZone::fixed(offset(-5))));
652 ///
653 /// // A time zone annotation name gets you a IANA time zone:
654 /// let pieces = Pieces::parse("2025-01-03T17:13-05[America/New_York]")?;
655 /// assert_eq!(pieces.to_time_zone()?, Some(TimeZone::get("America/New_York")?));
656 ///
657 /// // A time zone annotation name that doesn't exist gives you an error:
658 /// let pieces = Pieces::parse("2025-01-03T17:13-05[Australia/Bluey]")?;
659 /// assert_eq!(
660 /// pieces.to_time_zone().unwrap_err().to_string(),
661 /// "failed to find time zone `Australia/Bluey` in time zone database",
662 /// );
663 ///
664 /// # Ok::<(), Box<dyn std::error::Error>>(())
665 /// ```
666 #[inline]
667 pub fn to_time_zone(&self) -> Result<Option<TimeZone>, Error> {
668 self.to_time_zone_with(crate::tz::db())
669 }
670
671 /// A convenience routine for converting a time zone annotation, if
672 /// present, into a [`TimeZone`] using the given [`TimeZoneDatabase`].
673 ///
674 /// If no annotation is on this `Pieces`, then this returns `Ok(None)`.
675 ///
676 /// This may return an error if the time zone annotation is a name and it
677 /// couldn't be found in Jiff's global time zone database.
678 ///
679 /// # Example
680 ///
681 /// ```
682 /// use jiff::{fmt::temporal::Pieces, tz::TimeZone};
683 ///
684 /// // A time zone annotation name gets you a IANA time zone:
685 /// let pieces = Pieces::parse("2025-01-03T17:13-05[America/New_York]")?;
686 /// assert_eq!(
687 /// pieces.to_time_zone_with(jiff::tz::db())?,
688 /// Some(TimeZone::get("America/New_York")?),
689 /// );
690 ///
691 /// # Ok::<(), Box<dyn std::error::Error>>(())
692 /// ```
693 #[inline]
694 pub fn to_time_zone_with(
695 &self,
696 db: &TimeZoneDatabase,
697 ) -> Result<Option<TimeZone>, Error> {
698 let Some(ann) = self.time_zone_annotation() else { return Ok(None) };
699 ann.to_time_zone_with(db).map(Some)
700 }
701
702 /// Set the date on this `Pieces` to the one given.
703 ///
704 /// A `Date` is the minimal piece of information necessary to create a
705 /// `Pieces`. This method will override any previous setting.
706 ///
707 /// # Example
708 ///
709 /// ```
710 /// use jiff::{civil, fmt::temporal::Pieces, Timestamp};
711 ///
712 /// let pieces = Pieces::from(civil::date(2025, 1, 3));
713 /// assert_eq!(pieces.to_string(), "2025-01-03");
714 ///
715 /// // Alternatively, build a `Pieces` from another data type, and the
716 /// // date field will be automatically populated.
717 /// let pieces = Pieces::from(Timestamp::from_second(1735930208)?);
718 /// assert_eq!(pieces.date(), civil::date(2025, 1, 3));
719 /// assert_eq!(pieces.to_string(), "2025-01-03T18:50:08Z");
720 ///
721 /// # Ok::<(), Box<dyn std::error::Error>>(())
722 /// ```
723 #[inline]
724 pub fn with_date(self, date: Date) -> Pieces<'n> {
725 Pieces { date, ..self }
726 }
727
728 /// Set the time on this `Pieces` to the one given.
729 ///
730 /// Setting a [`Time`] on `Pieces` is optional. When formatting a
731 /// `Pieces` to a string, a missing `Time` may be omitted from the datetime
732 /// string in some cases. See [`Pieces::with_offset`] for more details.
733 ///
734 /// # Example
735 ///
736 /// ```
737 /// use jiff::{civil, fmt::temporal::Pieces};
738 ///
739 /// let pieces = Pieces::from(civil::date(2025, 1, 3))
740 /// .with_time(civil::time(13, 48, 0, 0));
741 /// assert_eq!(pieces.to_string(), "2025-01-03T13:48:00");
742 /// // Alternatively, build a `Pieces` from a `DateTime` directly:
743 /// let pieces = Pieces::from(civil::date(2025, 1, 3).at(13, 48, 0, 0));
744 /// assert_eq!(pieces.to_string(), "2025-01-03T13:48:00");
745 ///
746 /// # Ok::<(), Box<dyn std::error::Error>>(())
747 /// ```
748 #[inline]
749 pub fn with_time(self, time: Time) -> Pieces<'n> {
750 Pieces { time: Some(time), ..self }
751 }
752
753 /// Set the offset on this `Pieces` to the one given.
754 ///
755 /// Setting the offset on `Pieces` is optional.
756 ///
757 /// The type of offset is polymorphic, and includes anything that can be
758 /// infallibly converted into a [`PiecesOffset`]. This includes an
759 /// [`Offset`].
760 ///
761 /// This refers to the offset in the [RFC 3339] component of a Temporal
762 /// ISO 8601 datetime string.
763 ///
764 /// Since a string like `2025-01-03+11` is not valid, if a `Pieces` has
765 /// an offset set but no [`Time`] set, then formatting the `Pieces` will
766 /// write an explicit `Time` set to midnight.
767 ///
768 /// Note that this is distinct from [`Pieces::with_time_zone_offset`].
769 /// This routine sets the offset on the datetime, while
770 /// `Pieces::with_time_zone_offset` sets the offset inside the time zone
771 /// annotation. When the timestamp offset and the time zone annotation
772 /// offset are both present, then they must be equivalent or else the
773 /// datetime string is not a valid Temporal ISO 8601 string. However, a
774 /// `Pieces` will let you format a string with mismatching offsets.
775 ///
776 /// # Example
777 ///
778 /// This example shows how easily you can shoot yourself in the foot with
779 /// this routine:
780 ///
781 /// ```
782 /// use jiff::{fmt::temporal::{Pieces, TimeZoneAnnotation}, tz};
783 ///
784 /// let mut pieces = Pieces::parse("2025-01-03T07:55+02[+02]")?;
785 /// pieces = pieces.with_offset(tz::offset(-10));
786 /// // This is nonsense because the offsets don't match!
787 /// // And notice also that the instant that this timestamp refers to has
788 /// // changed.
789 /// assert_eq!(pieces.to_string(), "2025-01-03T07:55:00-10:00[+02:00]");
790 ///
791 /// # Ok::<(), Box<dyn std::error::Error>>(())
792 /// ```
793 ///
794 /// This exemplifies that `Pieces` is a mostly "dumb" type that passes
795 /// through the data it contains, even if it doesn't make sense.
796 ///
797 /// # Example: changing the offset can change the instant
798 ///
799 /// Consider this case where a `Pieces` is created directly from a
800 /// `Timestamp`, and then the offset is changed.
801 ///
802 /// ```
803 /// use jiff::{fmt::temporal::Pieces, tz, Timestamp};
804 ///
805 /// let pieces = Pieces::from(Timestamp::UNIX_EPOCH)
806 /// .with_offset(tz::offset(-5));
807 /// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00-05:00");
808 /// ```
809 ///
810 /// You might do this naively as a way of printing the timestamp of the
811 /// Unix epoch with an offset of `-05` from UTC. But the above does not
812 /// correspond to the Unix epoch:
813 ///
814 /// ```
815 /// use jiff::{Timestamp, ToSpan, Unit};
816 ///
817 /// let ts: Timestamp = "1970-01-01T00:00:00-05:00".parse()?;
818 /// assert_eq!(
819 /// ts.since((Unit::Hour, Timestamp::UNIX_EPOCH))?,
820 /// 5.hours().fieldwise(),
821 /// );
822 ///
823 /// # Ok::<(), Box<dyn std::error::Error>>(())
824 /// ```
825 ///
826 /// This further exemplifies how `Pieces` is just a "dumb" type that
827 /// passes through the data it contains.
828 ///
829 /// This specific example is also why `Pieces` has a `From` trait
830 /// implementation for `(Timestamp, Offset)`, which correspond more to
831 /// what you want:
832 ///
833 /// ```
834 /// use jiff::{fmt::temporal::Pieces, tz, Timestamp};
835 ///
836 /// let pieces = Pieces::from((Timestamp::UNIX_EPOCH, tz::offset(-5)));
837 /// assert_eq!(pieces.to_string(), "1969-12-31T19:00:00-05:00");
838 /// ```
839 ///
840 /// A decent mental model of `Pieces` is that setting fields on `Pieces`
841 /// can't change the values in memory of other fields.
842 ///
843 /// # Example: setting an offset forces a time to be written
844 ///
845 /// Consider these cases where formatting a `Pieces` won't write a
846 /// [`Time`]:
847 ///
848 /// ```
849 /// use jiff::fmt::temporal::Pieces;
850 ///
851 /// let pieces = Pieces::from(jiff::civil::date(2025, 1, 3));
852 /// assert_eq!(pieces.to_string(), "2025-01-03");
853 ///
854 /// let pieces = Pieces::from(jiff::civil::date(2025, 1, 3))
855 /// .with_time_zone_name("Africa/Cairo");
856 /// assert_eq!(pieces.to_string(), "2025-01-03[Africa/Cairo]");
857 /// ```
858 ///
859 /// This works because the resulting strings are valid. In particular, when
860 /// one parses a `2025-01-03[Africa/Cairo]` into a `ZonedDateTime`, it
861 /// results in a time component of midnight automatically (or more
862 /// precisely, the first instead of the corresponding day):
863 ///
864 /// ```
865 /// use jiff::{ZonedDateTime, civil::Time};
866 ///
867 /// let zdt: ZonedDateTime = "2025-01-03[Africa/Cairo]".parse()?;
868 /// assert_eq!(zdt.time(), Time::midnight());
869 ///
870 /// // tricksy tricksy, the first instant of 2015-10-18 in Sao Paulo is
871 /// // not midnight!
872 /// let zdt: ZonedDateTime = "2015-10-18[America/Sao_Paulo]".parse()?;
873 /// assert_eq!(zdt.time(), jiff::civil::time(1, 0, 0, 0));
874 /// // This happens because midnight didn't appear on the clocks in
875 /// // Sao Paulo on 2015-10-18. So if you try to parse a datetime with
876 /// // midnight, automatic disambiguation kicks in and chooses the time
877 /// // after the gap automatically:
878 /// let zdt: ZonedDateTime =
879 /// "2015-10-18T00:00:00[America/Sao_Paulo]".parse()?;
880 /// assert_eq!(zdt.time(), jiff::civil::time(1, 0, 0, 0));
881 ///
882 /// # Ok::<(), Box<dyn std::error::Error>>(())
883 /// ```
884 ///
885 /// However, if you have a date and an offset, then since things like
886 /// `2025-01-03+10` aren't valid Temporal ISO 8601 datetime strings, the
887 /// default midnight time is automatically written:
888 ///
889 /// ```
890 /// use jiff::{fmt::temporal::Pieces, tz};
891 ///
892 /// let pieces = Pieces::from(jiff::civil::date(2025, 1, 3))
893 /// .with_offset(tz::offset(-5));
894 /// assert_eq!(pieces.to_string(), "2025-01-03T00:00:00-05:00");
895 ///
896 /// let pieces = Pieces::from(jiff::civil::date(2025, 1, 3))
897 /// .with_offset(tz::offset(2))
898 /// .with_time_zone_name("Africa/Cairo");
899 /// assert_eq!(pieces.to_string(), "2025-01-03T00:00:00+02:00[Africa/Cairo]");
900 /// ```
901 ///
902 /// # Example: formatting a Zulu or `-00:00` offset
903 ///
904 /// A [`PiecesOffset`] encapsulates not just a numeric offset, but also
905 /// whether a `Z` or a signed zero are used. While it's uncommon to need
906 /// this, this permits one to format a `Pieces` using either of these
907 /// constructs:
908 ///
909 /// ```
910 /// use jiff::{
911 /// civil,
912 /// fmt::temporal::{Pieces, PiecesNumericOffset, PiecesOffset},
913 /// tz::Offset,
914 /// };
915 ///
916 /// let pieces = Pieces::from(civil::date(1970, 1, 1).at(0, 0, 0, 0))
917 /// .with_offset(Offset::UTC);
918 /// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00+00:00");
919 ///
920 /// let pieces = Pieces::from(civil::date(1970, 1, 1).at(0, 0, 0, 0))
921 /// .with_offset(PiecesOffset::Zulu);
922 /// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00Z");
923 ///
924 /// let pieces = Pieces::from(civil::date(1970, 1, 1).at(0, 0, 0, 0))
925 /// .with_offset(PiecesNumericOffset::from(Offset::UTC).with_negative_zero());
926 /// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00-00:00");
927 /// ```
928 ///
929 /// [RFC 3339]: https://www.rfc-editor.org/rfc/rfc3339
930 #[inline]
931 pub fn with_offset<T: Into<PiecesOffset>>(self, offset: T) -> Pieces<'n> {
932 Pieces { offset: Some(offset.into()), ..self }
933 }
934
935 /// Sets the time zone annotation on this `Pieces` to the given time zone
936 /// name.
937 ///
938 /// Setting a time zone annotation on `Pieces` is optional.
939 ///
940 /// This is a convenience routine for using
941 /// [`Pieces::with_time_zone_annotation`] with an explicitly constructed
942 /// [`TimeZoneAnnotation`] for a time zone name.
943 ///
944 /// # Example
945 ///
946 /// This example shows how easily you can shoot yourself in the foot with
947 /// this routine:
948 ///
949 /// ```
950 /// use jiff::fmt::temporal::{Pieces, TimeZoneAnnotation};
951 ///
952 /// let mut pieces = Pieces::parse("2025-01-03T07:55+02[Africa/Cairo]")?;
953 /// pieces = pieces.with_time_zone_name("Australia/Bluey");
954 /// // This is nonsense because `Australia/Bluey` isn't a valid time zone!
955 /// assert_eq!(pieces.to_string(), "2025-01-03T07:55:00+02:00[Australia/Bluey]");
956 ///
957 /// # Ok::<(), Box<dyn std::error::Error>>(())
958 /// ```
959 ///
960 /// This exemplifies that `Pieces` is a mostly "dumb" type that passes
961 /// through the data it contains, even if it doesn't make sense.
962 #[inline]
963 pub fn with_time_zone_name<'a>(self, name: &'a str) -> Pieces<'a> {
964 self.with_time_zone_annotation(TimeZoneAnnotation::from(name))
965 }
966
967 /// Sets the time zone annotation on this `Pieces` to the given offset.
968 ///
969 /// Setting a time zone annotation on `Pieces` is optional.
970 ///
971 /// This is a convenience routine for using
972 /// [`Pieces::with_time_zone_annotation`] with an explicitly constructed
973 /// [`TimeZoneAnnotation`] for a time zone offset.
974 ///
975 /// Note that this is distinct from [`Pieces::with_offset`]. This
976 /// routine sets the offset inside the time zone annotation, while
977 /// `Pieces::with_offset` sets the offset on the timestamp itself. When the
978 /// timestamp offset and the time zone annotation offset are both present,
979 /// then they must be equivalent or else the datetime string is not a valid
980 /// Temporal ISO 8601 string. However, a `Pieces` will let you format a
981 /// string with mismatching offsets.
982 ///
983 /// # Example
984 ///
985 /// This example shows how easily you can shoot yourself in the foot with
986 /// this routine:
987 ///
988 /// ```
989 /// use jiff::{fmt::temporal::{Pieces, TimeZoneAnnotation}, tz};
990 ///
991 /// let mut pieces = Pieces::parse("2025-01-03T07:55+02[Africa/Cairo]")?;
992 /// pieces = pieces.with_time_zone_offset(tz::offset(-7));
993 /// // This is nonsense because the offset `+02` does not match `-07`.
994 /// assert_eq!(pieces.to_string(), "2025-01-03T07:55:00+02:00[-07:00]");
995 ///
996 /// # Ok::<(), Box<dyn std::error::Error>>(())
997 /// ```
998 ///
999 /// This exemplifies that `Pieces` is a mostly "dumb" type that passes
1000 /// through the data it contains, even if it doesn't make sense.
1001 #[inline]
1002 pub fn with_time_zone_offset(self, offset: Offset) -> Pieces<'static> {
1003 self.with_time_zone_annotation(TimeZoneAnnotation::from(offset))
1004 }
1005
1006 /// Returns a new `Pieces` with the given time zone annotation.
1007 ///
1008 /// Setting a time zone annotation on `Pieces` is optional.
1009 ///
1010 /// You may find it more convenient to use
1011 /// [`Pieces::with_time_zone_name`] or [`Pieces::with_time_zone_offset`].
1012 ///
1013 /// # Example
1014 ///
1015 /// This example shows how easily you can shoot yourself in the foot with
1016 /// this routine:
1017 ///
1018 /// ```
1019 /// use jiff::fmt::temporal::{Pieces, TimeZoneAnnotation};
1020 ///
1021 /// let mut pieces = Pieces::parse("2025-01-03T07:55+02[Africa/Cairo]")?;
1022 /// pieces = pieces.with_time_zone_annotation(
1023 /// TimeZoneAnnotation::from("Canada/Yukon"),
1024 /// );
1025 /// // This is nonsense because the offset `+02` is never valid for the
1026 /// // `Canada/Yukon` time zone.
1027 /// assert_eq!(pieces.to_string(), "2025-01-03T07:55:00+02:00[Canada/Yukon]");
1028 ///
1029 /// # Ok::<(), Box<dyn std::error::Error>>(())
1030 /// ```
1031 ///
1032 /// This exemplifies that `Pieces` is a mostly "dumb" type that passes
1033 /// through the data it contains, even if it doesn't make sense.
1034 #[inline]
1035 pub fn with_time_zone_annotation<'a>(
1036 self,
1037 ann: TimeZoneAnnotation<'a>,
1038 ) -> Pieces<'a> {
1039 Pieces { time_zone_annotation: Some(ann), ..self }
1040 }
1041
1042 /// Converts this `Pieces` into an "owned" value whose lifetime is
1043 /// `'static`.
1044 ///
1045 /// The "owned" value in this context refers to the time zone annotation
1046 /// name, if present. For example, `Canada/Yukon` in
1047 /// `2025-01-03T07:55-07[Canada/Yukon]`. When parsing into a `Pieces`,
1048 /// the time zone annotation name is borrowed. But callers may find it more
1049 /// convenient to work with an owned value. By calling this method, the
1050 /// borrowed string internally will be copied into a new string heap
1051 /// allocation.
1052 ///
1053 /// If `Pieces` doesn't have a time zone annotation, is already owned or
1054 /// the time zone annotation is an offset, then this is a no-op.
1055 #[cfg(feature = "alloc")]
1056 #[inline]
1057 pub fn into_owned(self) -> Pieces<'static> {
1058 Pieces {
1059 date: self.date,
1060 time: self.time,
1061 offset: self.offset,
1062 time_zone_annotation: self
1063 .time_zone_annotation
1064 .map(|ann| ann.into_owned()),
1065 }
1066 }
1067}
1068
1069impl From<Date> for Pieces<'static> {
1070 #[inline]
1071 fn from(date: Date) -> Pieces<'static> {
1072 Pieces { date, time: None, offset: None, time_zone_annotation: None }
1073 }
1074}
1075
1076impl From<DateTime> for Pieces<'static> {
1077 #[inline]
1078 fn from(dt: DateTime) -> Pieces<'static> {
1079 Pieces::from(dt.date()).with_time(dt.time())
1080 }
1081}
1082
1083impl From<Timestamp> for Pieces<'static> {
1084 #[inline]
1085 fn from(ts: Timestamp) -> Pieces<'static> {
1086 let dt = Offset::UTC.to_datetime(ts);
1087 Pieces::from(dt).with_offset(PiecesOffset::Zulu)
1088 }
1089}
1090
1091impl From<(Timestamp, Offset)> for Pieces<'static> {
1092 #[inline]
1093 fn from((ts, offset): (Timestamp, Offset)) -> Pieces<'static> {
1094 Pieces::from(offset.to_datetime(ts)).with_offset(offset)
1095 }
1096}
1097
1098impl<'a> From<&'a ZonedDateTime> for Pieces<'a> {
1099 #[inline]
1100 fn from(zdt: &'a ZonedDateTime) -> Pieces<'a> {
1101 let mut pieces =
1102 Pieces::from(zdt.datetime()).with_offset(zdt.offset());
1103 if let Some(name) = zdt.time_zone().iana_name() {
1104 pieces = pieces.with_time_zone_name(name);
1105 } else {
1106 pieces = pieces.with_time_zone_offset(zdt.offset());
1107 }
1108 pieces
1109 }
1110}
1111
1112impl<'n> core::fmt::Display for Pieces<'n> {
1113 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1114 use crate::fmt::StdFmtWrite;
1115
1116 let precision =
1117 f.precision().map(|p| u8::try_from(p).unwrap_or(u8::MAX));
1118 super::DateTimePrinter::new()
1119 .precision(precision)
1120 .print_pieces(self, StdFmtWrite(f))
1121 .map_err(|_| core::fmt::Error)
1122 }
1123}
1124
1125/// An offset parsed from a Temporal ISO 8601 datetime string, for use with
1126/// [`Pieces`].
1127///
1128/// One can almost think of this as effectively equivalent to an `Offset`. And
1129/// indeed, all `PiecesOffset` values can be convert to an `Offset`. However,
1130/// some offsets in a datetime string have a different connotation that can't
1131/// be captured by an `Offset`.
1132///
1133/// For example, the offsets `Z`, `-00:00` and `+00:00` all map to
1134/// [`Offset::UTC`] after parsing. However, `Z` and `-00:00` generally
1135/// indicate that the offset from local time is unknown, where as `+00:00`
1136/// indicates that the offset from local is _known_ and is zero. This type
1137/// permits callers to inspect what offset was actually written.
1138///
1139/// # Example
1140///
1141/// This example shows how one can create Temporal ISO 8601 datetime strings
1142/// with `+00:00`, `-00:00` or `Z` offsets.
1143///
1144/// ```
1145/// use jiff::{
1146/// fmt::temporal::{Pieces, PiecesNumericOffset},
1147/// tz::Offset,
1148/// Timestamp,
1149/// };
1150///
1151/// // If you create a `Pieces` from a `Timestamp` with a UTC offset,
1152/// // then this is interpreted as "the offset from UTC is known and is
1153/// // zero."
1154/// let pieces = Pieces::from((Timestamp::UNIX_EPOCH, Offset::UTC));
1155/// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00+00:00");
1156///
1157/// // Otherwise, if you create a `Pieces` from just a `Timestamp` with
1158/// // no offset, then it is interpreted as "the offset from UTC is not
1159/// // known." Typically, this is rendered with `Z` for "Zulu":
1160/// let pieces = Pieces::from(Timestamp::UNIX_EPOCH);
1161/// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00Z");
1162///
1163/// // But it might be the case that you want to use `-00:00` instead,
1164/// // perhaps to conform to some existing convention or legacy
1165/// // applications that require it:
1166/// let pieces = Pieces::from(Timestamp::UNIX_EPOCH)
1167/// .with_offset(
1168/// PiecesNumericOffset::from(Offset::UTC).with_negative_zero(),
1169/// );
1170/// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00-00:00");
1171/// ```
1172///
1173/// Without `Pieces`, it's not otherwise possible to emit a `-00:00` offset.
1174/// For example,
1175/// [`DateTimePrinter::print_timestamp`](crate::fmt::temporal::DateTimePrinter::print_timestamp)
1176/// will always emit `Z`, which is consider semantically identical to `-00:00`
1177/// by [RFC 9557]. There's no specific use case where it's expected that you
1178/// should need to write `-00:00` instead of `Z`, but it's conceivable legacy
1179/// or otherwise inflexible applications might want it. Or perhaps, in some
1180/// systems, there is a distinction to draw between `Z` and `-00:00`.
1181///
1182/// [RFC 9557]: https://www.rfc-editor.org/rfc/rfc9557.html
1183#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1184#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1185#[non_exhaustive]
1186pub enum PiecesOffset {
1187 /// The "Zulu" offset, corresponding to UTC in a context where the offset
1188 /// for civil time is unknown or unavailable.
1189 ///
1190 /// [RFC 9557] defines this as equivalent in semantic meaning to `-00:00`:
1191 ///
1192 /// > If the time in UTC is known, but the offset to local time is unknown,
1193 /// > this can be represented with an offset of `Z`. (The original version
1194 /// > of this specification provided `-00:00` for this purpose, which is
1195 /// > not allowed by ISO-8601:2000 and therefore is less interoperable;
1196 /// > Section 3.3 of RFC 5322 describes a related convention for email,
1197 /// > which does not have this problem). This differs semantically from an
1198 /// > offset of `+00:00`, which implies that UTC is the preferred reference
1199 /// > point for the specified time.
1200 ///
1201 /// [RFC 9557]: https://www.rfc-editor.org/rfc/rfc9557
1202 Zulu,
1203 /// A specific numeric offset, including whether the parsed sign is
1204 /// negative.
1205 ///
1206 /// The sign is usually redundant, since an `Offset` is itself signed. But
1207 /// it can be used to distinguish between `+00:00` (`+00` is the preferred
1208 /// offset) and `-00:00` (`+00` is what should be used, but only because
1209 /// the offset to local time is not known). Generally speaking, one should
1210 /// regard `-00:00` as equivalent to `Z`, per RFC 9557.
1211 Numeric(PiecesNumericOffset),
1212}
1213
1214impl PiecesOffset {
1215 /// Converts this offset to a concrete numeric offset in all cases.
1216 ///
1217 /// If this was a `Z` or a `-00:00` offset, then `Offset::UTC` is returned.
1218 /// In all other cases, the underlying numeric offset is returned as-is.
1219 ///
1220 /// # Example
1221 ///
1222 /// ```
1223 /// use jiff::{
1224 /// fmt::temporal::{Pieces, PiecesNumericOffset, PiecesOffset},
1225 /// tz::Offset,
1226 /// };
1227 ///
1228 /// let pieces = Pieces::parse("1970-01-01T00:00:00Z")?;
1229 /// let off = pieces.offset().unwrap();
1230 /// // Parsed as Zulu.
1231 /// assert_eq!(off, PiecesOffset::Zulu);
1232 /// // Gets converted from Zulu to UTC, i.e., just zero.
1233 /// assert_eq!(off.to_numeric_offset(), Offset::UTC);
1234 ///
1235 /// let pieces = Pieces::parse("1970-01-01T00:00:00-00:00")?;
1236 /// let off = pieces.offset().unwrap();
1237 /// // Parsed as a negative zero.
1238 /// assert_eq!(off, PiecesOffset::from(
1239 /// PiecesNumericOffset::from(Offset::UTC).with_negative_zero(),
1240 /// ));
1241 /// // Gets converted from -00:00 to UTC, i.e., just zero.
1242 /// assert_eq!(off.to_numeric_offset(), Offset::UTC);
1243 ///
1244 /// let pieces = Pieces::parse("1970-01-01T00:00:00+00:00")?;
1245 /// let off = pieces.offset().unwrap();
1246 /// // Parsed as a positive zero.
1247 /// assert_eq!(off, PiecesOffset::from(
1248 /// PiecesNumericOffset::from(Offset::UTC),
1249 /// ));
1250 /// // Gets converted from -00:00 to UTC, i.e., just zero.
1251 /// assert_eq!(off.to_numeric_offset(), Offset::UTC);
1252 ///
1253 /// # Ok::<(), Box<dyn std::error::Error>>(())
1254 /// ```
1255 #[inline]
1256 pub fn to_numeric_offset(&self) -> Offset {
1257 match *self {
1258 PiecesOffset::Zulu => Offset::UTC,
1259 // -00:00 and +00:00 both collapse to zero here.
1260 PiecesOffset::Numeric(ref noffset) => noffset.offset(),
1261 }
1262 }
1263}
1264
1265impl From<Offset> for PiecesOffset {
1266 #[inline]
1267 fn from(offset: Offset) -> PiecesOffset {
1268 PiecesOffset::from(PiecesNumericOffset::from(offset))
1269 }
1270}
1271
1272impl From<PiecesNumericOffset> for PiecesOffset {
1273 #[inline]
1274 fn from(offset: PiecesNumericOffset) -> PiecesOffset {
1275 PiecesOffset::Numeric(offset)
1276 }
1277}
1278
1279/// A specific numeric offset, including the sign of the offset, for use with
1280/// [`Pieces`].
1281///
1282/// # Signedness
1283///
1284/// The sign attached to this type is usually redundant, since the underlying
1285/// [`Offset`] is itself signed. But it can be used to distinguish between
1286/// `+00:00` (`+00` is the preferred offset) and `-00:00` (`+00` is what should
1287/// be used, but only because the offset to local time is not known). Generally
1288/// speaking, one should regard `-00:00` as equivalent to `Z`, per [RFC 9557].
1289///
1290/// [RFC 9557]: https://www.rfc-editor.org/rfc/rfc9557
1291#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1292#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1293pub struct PiecesNumericOffset {
1294 offset: Offset,
1295 is_negative: bool,
1296}
1297
1298impl PiecesNumericOffset {
1299 /// Returns the numeric offset.
1300 ///
1301 /// # Example
1302 ///
1303 /// ```
1304 /// use jiff::{
1305 /// fmt::temporal::{Pieces, PiecesOffset},
1306 /// tz::Offset,
1307 /// };
1308 ///
1309 /// let pieces = Pieces::parse("1970-01-01T00:00:00-05:30")?;
1310 /// let off = match pieces.offset().unwrap() {
1311 /// PiecesOffset::Numeric(off) => off,
1312 /// _ => unreachable!(),
1313 /// };
1314 /// // This is really only useful if you care that an actual
1315 /// // numeric offset was written and not, e.g., `Z`. Otherwise,
1316 /// // you could just use `PiecesOffset::to_numeric_offset`.
1317 /// assert_eq!(
1318 /// off.offset(),
1319 /// Offset::from_seconds(-5 * 60 * 60 - 30 * 60).unwrap(),
1320 /// );
1321 ///
1322 /// # Ok::<(), Box<dyn std::error::Error>>(())
1323 /// ```
1324 #[inline]
1325 pub fn offset(&self) -> Offset {
1326 self.offset
1327 }
1328
1329 /// Returns whether the sign of the offset is negative or not.
1330 ///
1331 /// When formatting a [`Pieces`] to a string, this is _only_ used to
1332 /// determine the rendered sign when the [`Offset`] is itself zero. In
1333 /// all other cases, the sign rendered matches the sign of the `Offset`.
1334 ///
1335 /// Since `Offset` does not keep track of a sign when its value is zero,
1336 /// when using the `From<Offset>` trait implementation for this type,
1337 /// `is_negative` is always set to `false` when the offset is zero.
1338 ///
1339 /// # Example
1340 ///
1341 /// ```
1342 /// use jiff::{
1343 /// fmt::temporal::{Pieces, PiecesOffset},
1344 /// tz::Offset,
1345 /// };
1346 ///
1347 /// let pieces = Pieces::parse("1970-01-01T00:00:00-00:00")?;
1348 /// let off = match pieces.offset().unwrap() {
1349 /// PiecesOffset::Numeric(off) => off,
1350 /// _ => unreachable!(),
1351 /// };
1352 /// // The numeric offset component in this case is
1353 /// // indistiguisable from `Offset::UTC`. This is
1354 /// // because an `Offset` does not use different
1355 /// // representations for negative and positive zero.
1356 /// assert_eq!(off.offset(), Offset::UTC);
1357 /// // This is where `is_negative` comes in handy:
1358 /// assert_eq!(off.is_negative(), true);
1359 ///
1360 /// # Ok::<(), Box<dyn std::error::Error>>(())
1361 /// ```
1362 #[inline]
1363 pub fn is_negative(&self) -> bool {
1364 self.is_negative
1365 }
1366
1367 /// Sets this numeric offset to use `-00:00` if and only if the offset
1368 /// is zero.
1369 ///
1370 /// # Example
1371 ///
1372 /// ```
1373 /// use jiff::{
1374 /// fmt::temporal::{Pieces, PiecesNumericOffset},
1375 /// tz::Offset,
1376 /// Timestamp,
1377 /// };
1378 ///
1379 /// // If you create a `Pieces` from a `Timestamp` with a UTC offset,
1380 /// // then this is interpreted as "the offset from UTC is known and is
1381 /// // zero."
1382 /// let pieces = Pieces::from((Timestamp::UNIX_EPOCH, Offset::UTC));
1383 /// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00+00:00");
1384 ///
1385 /// // Otherwise, if you create a `Pieces` from just a `Timestamp` with
1386 /// // no offset, then it is interpreted as "the offset from UTC is not
1387 /// // known." Typically, this is rendered with `Z` for "Zulu":
1388 /// let pieces = Pieces::from(Timestamp::UNIX_EPOCH);
1389 /// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00Z");
1390 ///
1391 /// // But it might be the case that you want to use `-00:00` instead,
1392 /// // perhaps to conform to some existing convention or legacy
1393 /// // applications that require it:
1394 /// let pieces = Pieces::from(Timestamp::UNIX_EPOCH)
1395 /// .with_offset(
1396 /// PiecesNumericOffset::from(Offset::UTC).with_negative_zero(),
1397 /// );
1398 /// assert_eq!(pieces.to_string(), "1970-01-01T00:00:00-00:00");
1399 /// ```
1400 #[inline]
1401 pub fn with_negative_zero(self) -> PiecesNumericOffset {
1402 PiecesNumericOffset { is_negative: true, ..self }
1403 }
1404}
1405
1406impl From<Offset> for PiecesNumericOffset {
1407 #[inline]
1408 fn from(offset: Offset) -> PiecesNumericOffset {
1409 // This can of course never return a -00:00 offset, only +00:00.
1410 PiecesNumericOffset { offset, is_negative: offset.is_negative() }
1411 }
1412}
1413
1414/// An [RFC 9557] time zone annotation, for use with [`Pieces`].
1415///
1416/// A time zone annotation is either a time zone name (typically an IANA time
1417/// zone identifier) like `America/New_York`, or an offset like `-05:00`. This
1418/// is normally an implementation detail of parsing into a [`ZonedDateTime`],
1419/// but the raw annotation can be accessed via [`Pieces::time_zone_annotation`]
1420/// after parsing into a [`Pieces`].
1421///
1422/// The lifetime parameter refers to the lifetime of the time zone
1423/// name. The lifetime is static when the time zone annotation is
1424/// offset or if the name is owned. An owned value can be produced via
1425/// [`TimeZoneAnnotation::into_owned`] when the `alloc` crate feature is
1426/// enabled.
1427///
1428/// # Construction
1429///
1430/// If you're using [`Pieces`], then its [`Pieces::with_time_zone_name`] and
1431/// [`Pieces::with_time_zone_offset`] methods should absolve you of needing to
1432/// build values of this type explicitly. But if the need arises, there are
1433/// `From` impls for `&str` (time zone annotation name) and [`Offset`] (time
1434/// zone annotation offset) for this type.
1435///
1436/// # Example
1437///
1438/// ```
1439/// use jiff::{fmt::temporal::{Pieces, TimeZoneAnnotation}, tz::offset};
1440///
1441/// // A time zone annotation from a name:
1442/// let pieces = Pieces::parse("2025-01-02T16:47-05[America/New_York]")?;
1443/// assert_eq!(
1444/// pieces.time_zone_annotation().unwrap(),
1445/// &TimeZoneAnnotation::from("America/New_York"),
1446/// );
1447///
1448/// // A time zone annotation from an offset:
1449/// let pieces = Pieces::parse("2025-01-02T16:47-05[-05:00]")?;
1450/// assert_eq!(
1451/// pieces.time_zone_annotation().unwrap(),
1452/// &TimeZoneAnnotation::from(offset(-5)),
1453/// );
1454///
1455/// # Ok::<(), Box<dyn std::error::Error>>(())
1456/// ```
1457///
1458/// [RFC 9557]: https://www.rfc-editor.org/rfc/rfc9557.html
1459#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1460#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1461pub struct TimeZoneAnnotation<'n> {
1462 pub(crate) kind: TimeZoneAnnotationKind<'n>,
1463 /// Whether the annotation is marked as "critical," i.e., with a
1464 /// `!` prefix. When enabled, it's supposed to make the annotation
1465 /// un-ignorable.
1466 ///
1467 /// This is basically unused. And there's no way for callers to flip this
1468 /// switch currently. But it can be queried after parsing. Jiff also
1469 /// doesn't alter its behavior based on this flag. In particular, Jiff
1470 /// basically always behaves as if `critical` is true.
1471 pub(crate) critical: bool,
1472}
1473
1474impl<'n> TimeZoneAnnotation<'n> {
1475 /// Returns the "kind" of this annotation. The kind is either a name or an
1476 /// offset.
1477 ///
1478 /// # Example
1479 ///
1480 /// ```
1481 /// use jiff::fmt::temporal::{Pieces, TimeZoneAnnotation};
1482 ///
1483 /// // A time zone annotation from a name, which doesn't necessarily have
1484 /// // to point to a valid IANA time zone.
1485 /// let pieces = Pieces::parse("2025-01-02T16:47-05[Australia/Bluey]")?;
1486 /// assert_eq!(
1487 /// pieces.time_zone_annotation().unwrap(),
1488 /// &TimeZoneAnnotation::from("Australia/Bluey"),
1489 /// );
1490 ///
1491 /// # Ok::<(), Box<dyn std::error::Error>>(())
1492 /// ```
1493 #[inline]
1494 pub fn kind(&self) -> &TimeZoneAnnotationKind<'n> {
1495 &self.kind
1496 }
1497
1498 /// Returns true when this time zone is marked as "critical." This occurs
1499 /// when the time zone annotation is preceded by a `!`. It is meant to
1500 /// signify that, basically, implementations should error if the annotation
1501 /// is invalid in some way. And when it's absent, it's left up to the
1502 /// implementation's discretion about what to do (including silently
1503 /// ignoring the invalid annotation).
1504 ///
1505 /// Generally speaking, Jiff ignores this altogether for time zone
1506 /// annotations and behaves as if it's always true. But it's exposed here
1507 /// for callers to query in case it's useful.
1508 ///
1509 /// # Example
1510 ///
1511 /// ```
1512 /// use jiff::fmt::temporal::{Pieces, TimeZoneAnnotation};
1513 ///
1514 /// // not critical
1515 /// let pieces = Pieces::parse("2025-01-02T16:47-05[Australia/Bluey]")?;
1516 /// assert_eq!(
1517 /// Some(false),
1518 /// pieces.time_zone_annotation().map(|a| a.is_critical()),
1519 /// );
1520 ///
1521 /// // critical
1522 /// let pieces = Pieces::parse("2025-01-02T16:47-05[!Australia/Bluey]")?;
1523 /// assert_eq!(
1524 /// Some(true),
1525 /// pieces.time_zone_annotation().map(|a| a.is_critical()),
1526 /// );
1527 ///
1528 /// # Ok::<(), Box<dyn std::error::Error>>(())
1529 /// ```
1530 #[inline]
1531 pub fn is_critical(&self) -> bool {
1532 self.critical
1533 }
1534
1535 /// A convenience routine for converting this annotation into a time zone.
1536 ///
1537 /// This can fail if the annotation contains a name that couldn't be found
1538 /// in the global time zone database. If you need to use something other
1539 /// than the global time zone database, then use
1540 /// [`TimeZoneAnnotation::to_time_zone_with`].
1541 ///
1542 /// Note that it may be more convenient to use
1543 /// [`Pieces::to_time_zone`].
1544 ///
1545 /// # Example
1546 ///
1547 /// ```
1548 /// use jiff::{fmt::temporal::Pieces, tz::TimeZone};
1549 ///
1550 /// let pieces = Pieces::parse("2025-01-02T16:47-05[Australia/Hobart]")?;
1551 /// let ann = pieces.time_zone_annotation().unwrap();
1552 /// assert_eq!(
1553 /// ann.to_time_zone().unwrap(),
1554 /// TimeZone::get("Australia/Hobart").unwrap(),
1555 /// );
1556 ///
1557 /// let pieces = Pieces::parse("2025-01-02T16:47-05[Australia/Bluey]")?;
1558 /// let ann = pieces.time_zone_annotation().unwrap();
1559 /// assert_eq!(
1560 /// ann.to_time_zone().unwrap_err().to_string(),
1561 /// "failed to find time zone `Australia/Bluey` in time zone database",
1562 /// );
1563 ///
1564 /// # Ok::<(), Box<dyn std::error::Error>>(())
1565 /// ```
1566 #[inline]
1567 pub fn to_time_zone(&self) -> Result<TimeZone, Error> {
1568 self.to_time_zone_with(crate::tz::db())
1569 }
1570
1571 /// This is like [`TimeZoneAnnotation::to_time_zone`], but permits the
1572 /// caller to pass in their own time zone database.
1573 ///
1574 /// This can fail if the annotation contains a name that couldn't be found
1575 /// in the global time zone database. If you need to use something other
1576 /// than the global time zone database, then use
1577 /// [`TimeZoneAnnotation::to_time_zone_with`].
1578 ///
1579 /// Note that it may be more convenient to use
1580 /// [`Pieces::to_time_zone_with`].
1581 ///
1582 /// # Example
1583 ///
1584 /// ```
1585 /// use jiff::{fmt::temporal::Pieces, tz::TimeZone};
1586 ///
1587 /// let pieces = Pieces::parse("2025-01-02T16:47-05[Australia/Hobart]")?;
1588 /// let ann = pieces.time_zone_annotation().unwrap();
1589 /// assert_eq!(
1590 /// ann.to_time_zone_with(jiff::tz::db()).unwrap(),
1591 /// TimeZone::get("Australia/Hobart").unwrap(),
1592 /// );
1593 ///
1594 /// # Ok::<(), Box<dyn std::error::Error>>(())
1595 /// ```
1596 #[inline]
1597 pub fn to_time_zone_with(
1598 &self,
1599 db: &TimeZoneDatabase,
1600 ) -> Result<TimeZone, Error> {
1601 // NOTE: We don't currently utilize the critical flag here. Temporal
1602 // seems to ignore it. It's not quite clear what else we'd do with it,
1603 // particularly given that we provide a way to do conflict resolution
1604 // between offsets and time zones.
1605 let tz = match *self.kind() {
1606 TimeZoneAnnotationKind::Named(ref name) => {
1607 db.get(name.as_str())?
1608 }
1609 TimeZoneAnnotationKind::Offset(offset) => TimeZone::fixed(offset),
1610 };
1611 Ok(tz)
1612 }
1613
1614 /// Converts this time zone annotation into an "owned" value whose lifetime
1615 /// is `'static`.
1616 ///
1617 /// If this was already an "owned" value or a time zone annotation offset,
1618 /// then this is a no-op.
1619 #[cfg(feature = "alloc")]
1620 #[inline]
1621 pub fn into_owned(self) -> TimeZoneAnnotation<'static> {
1622 TimeZoneAnnotation {
1623 kind: self.kind.into_owned(),
1624 critical: self.critical,
1625 }
1626 }
1627}
1628
1629impl<'n> From<&'n str> for TimeZoneAnnotation<'n> {
1630 fn from(string: &'n str) -> TimeZoneAnnotation<'n> {
1631 let kind = TimeZoneAnnotationKind::from(string);
1632 TimeZoneAnnotation { kind, critical: false }
1633 }
1634}
1635
1636impl From<Offset> for TimeZoneAnnotation<'static> {
1637 fn from(offset: Offset) -> TimeZoneAnnotation<'static> {
1638 let kind = TimeZoneAnnotationKind::from(offset);
1639 TimeZoneAnnotation { kind, critical: false }
1640 }
1641}
1642
1643/// The kind of time zone found in an [RFC 9557] timestamp, for use with
1644/// [`Pieces`].
1645///
1646/// The lifetime parameter refers to the lifetime of the time zone
1647/// name. The lifetime is static when the time zone annotation is
1648/// offset or if the name is owned. An owned value can be produced via
1649/// [`TimeZoneAnnotation::into_owned`] when the `alloc` crate feature is
1650/// enabled.
1651///
1652/// [RFC 9557]: https://www.rfc-editor.org/rfc/rfc9557.html
1653#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1654#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1655#[non_exhaustive]
1656pub enum TimeZoneAnnotationKind<'n> {
1657 /// The time zone annotation is a name, usually an IANA time zone
1658 /// identifier. For example, `America/New_York`.
1659 Named(TimeZoneAnnotationName<'n>),
1660 /// The time zone annotation is an offset. For example, `-05:00`.
1661 Offset(Offset),
1662}
1663
1664impl<'n> TimeZoneAnnotationKind<'n> {
1665 /// Converts this time zone annotation kind into an "owned" value whose
1666 /// lifetime is `'static`.
1667 ///
1668 /// If this was already an "owned" value or a time zone annotation offset,
1669 /// then this is a no-op.
1670 #[cfg(feature = "alloc")]
1671 #[inline]
1672 pub fn into_owned(self) -> TimeZoneAnnotationKind<'static> {
1673 match self {
1674 TimeZoneAnnotationKind::Named(named) => {
1675 TimeZoneAnnotationKind::Named(named.into_owned())
1676 }
1677 TimeZoneAnnotationKind::Offset(offset) => {
1678 TimeZoneAnnotationKind::Offset(offset)
1679 }
1680 }
1681 }
1682}
1683
1684impl<'n> From<&'n str> for TimeZoneAnnotationKind<'n> {
1685 fn from(string: &'n str) -> TimeZoneAnnotationKind<'n> {
1686 let name = TimeZoneAnnotationName::from(string);
1687 TimeZoneAnnotationKind::Named(name)
1688 }
1689}
1690
1691impl From<Offset> for TimeZoneAnnotationKind<'static> {
1692 fn from(offset: Offset) -> TimeZoneAnnotationKind<'static> {
1693 TimeZoneAnnotationKind::Offset(offset)
1694 }
1695}
1696
1697/// A time zone annotation parsed from a datetime string.
1698///
1699/// By default, a time zone annotation name borrows its name from the
1700/// input it was parsed from. When the `alloc` feature is enabled,
1701/// callers can de-couple the annotation from the parsed input with
1702/// [`TimeZoneAnnotationName::into_owned`].
1703///
1704/// A value of this type is usually found via [`Pieces::time_zone_annotation`],
1705/// but callers can also construct one via this type's `From<&str>` trait
1706/// implementation if necessary.
1707#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1708#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1709pub struct TimeZoneAnnotationName<'n> {
1710 name: StringCow<'n>,
1711}
1712
1713impl<'n> TimeZoneAnnotationName<'n> {
1714 /// Returns the name of this time zone annotation as a string slice.
1715 ///
1716 /// Note that the lifetime of the string slice returned is tied to the
1717 /// lifetime of this time zone annotation. This may be shorter than the
1718 /// lifetime of the string, `'n`, in this annotation.
1719 #[inline]
1720 pub fn as_str<'a>(&'a self) -> &'a str {
1721 self.name.as_str()
1722 }
1723
1724 /// Converts this time zone annotation name into an "owned" value whose
1725 /// lifetime is `'static`.
1726 ///
1727 /// If this was already an "owned" value, then this is a no-op.
1728 #[cfg(feature = "alloc")]
1729 #[inline]
1730 pub fn into_owned(self) -> TimeZoneAnnotationName<'static> {
1731 TimeZoneAnnotationName { name: self.name.into_owned() }
1732 }
1733}
1734
1735impl<'n> From<&'n str> for TimeZoneAnnotationName<'n> {
1736 fn from(string: &'n str) -> TimeZoneAnnotationName<'n> {
1737 TimeZoneAnnotationName { name: StringCow::from(string) }
1738 }
1739}