jiff 0.1.15

A date-time library that encourages you to jump into the pit of success. This library is heavily inspired by the Temporal project.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
/*!
A hybrid format derived from [RFC 3339], [RFC 9557] and [ISO 8601].

This module provides an implementation of the [Temporal ISO 8601 grammar]. The
API is spread out over parsers and printers for datetimes and spans.

Note that for most use cases, you should be using the corresponding
[`Display`](std::fmt::Display) or [`FromStr`](std::str::FromStr) trait
implementations for printing and parsing respectively. This module provides
a "lower level" API for configuring the behavior of printing and parsing,
including the ability to parse from byte strings (i.e., `&[u8]`).

# Date and time format

The specific format supported depends on what kind of type you're trying to
parse into. Here are some examples to give a general idea:

* `02:21:58` parses into a [`civil::Time`].
* `2020-08-21` parses into a [`civil::Date`].
* `2020-08-21T02:21:58` and `2020-08-21 02:21:58` both parse into a
  [`civil::DateTime`].
* `2020-08-21T02:21:58-04` parses into an [`Timestamp`].
* `2020-08-21T02:21:58-04[America/New_York]` parses into a [`Zoned`].

Smaller types can generally be parsed from strings representing a bigger type.
For example, a `civil::Date` can be parsed from `2020-08-21T02:21:58`.

As mentioned above, the datetime format supported by Jiff is a hybrid of the
"best" parts of [RFC 3339], [RFC 9557] and [ISO 8601]. Generally speaking, [RFC
3339] and [RFC 9557] are supported in their entirety, but not all of ISO 8601
is. For example, `2024-06-16T10.5` is a valid ISO 8601 datetime, but isn't
supported by Jiff. (Only fractional seconds are supported.)

Some additional details worth noting:

* Parsing `Zoned` values requires a datetime string with a time zone
annotation like `[America/New_York]` or `[-07:00]`. If you need to parse a
datetime without a time zone annotation (but with an offset), then you should
parse it as an [`Timestamp`]. From there, it can be converted to a `Zoned` via
[`Timestamp::to_zoned`].
* When parsing `Zoned` values, ambiguous datetimes are handled via the
[`DateTimeParser::disambiguation`] configuration. By default, a "compatible"
mode is used where the earlier time is selected in a backward transition, while
the later time is selected in a forward transition.
* When parsing `Zoned` values, conflicts between the offset and the time zone
in the datetime string are handled via the [`DateTimeParser::offset_conflict`]
configuration. By default, any inconsistency between the offset and the time
zone results in a parse error.
* When parsing civil types like `civil::DateTime`, it's always an error if the
datetime string has a `Z` (Zulu) offset. It's an error since interpreting such
strings as civil time is usually a bug.
* In all cases, the `T` designator separating the date and time may be an ASCII
space instead.

The complete datetime format supported is described by the
[Temporal ISO 8601 grammar].

# Span format

To a first approximation, the span format supported roughly corresponds to this
regular expression:

```text
P(\d+y)?(\d+m)?(\d+w)?(\d+d)?(T(\d+h)?(\d+m)?(\d+s)?)?
```

But there are some details not easily captured by a simple regular expression:

* At least one unit must be specified. To write a zero span, specify `0` for
any unit. For example, `P0d` and `PT0s` are equivalent.
* The format is case insensitive. The printer will by default capitalize the
`P` and `T` designators, but lowercase the unit designators.
* Hours, minutes or seconds may be fractional. And the only units that may be
fractional are the lowest units.
* A span like `P99999999999y` is invalid because it exceeds the allowable range
of time representable by a [`Span`].

This is, roughly speaking, a subset of what [ISO 8601] specifies. It isn't
strictly speaking a subset since Jiff (like Temporal) permits week units to be
mixed with other units.

Here are some examples:

```
use jiff::{Span, ToSpan};

let spans = [
    ("P40D", 40.days()),
    ("P1y1d", 1.year().days(1)),
    ("P3dT4h59m", 3.days().hours(4).minutes(59)),
    ("PT2H30M", 2.hours().minutes(30)),
    ("P1m", 1.month()),
    ("P1w", 1.week()),
    ("P1w4d", 1.week().days(4)),
    ("PT1m", 1.minute()),
    ("PT0.0021s", 2.milliseconds().microseconds(100)),
    ("PT0s", 0.seconds()),
    ("P0d", 0.seconds()),
    (
        "P1y1m1dT1h1m1.1s",
        1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
    ),
];
for (string, span) in spans {
    let parsed: Span = string.parse()?;
    assert_eq!(span, parsed, "result of parsing {string:?}");
}

# Ok::<(), Box<dyn std::error::Error>>(())
```

One can also parse ISO 8601 durations into a [`SignedDuration`], but units are
limited to hours or smaller:

```
use jiff::SignedDuration;

let durations = [
    ("PT2H30M", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
    ("PT2.5h", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
    ("PT1m", SignedDuration::from_mins(1)),
    ("PT1.5m", SignedDuration::from_secs(90)),
    ("PT0.0021s", SignedDuration::new(0, 2_100_000)),
    ("PT0s", SignedDuration::ZERO),
    ("PT0.000000001s", SignedDuration::from_nanos(1)),
];
for (string, duration) in durations {
    let parsed: SignedDuration = string.parse()?;
    assert_eq!(duration, parsed, "result of parsing {string:?}");
}

# Ok::<(), Box<dyn std::error::Error>>(())
```

The complete span format supported is described by the [Temporal ISO 8601
grammar].

# Differences with Temporal

Jiff implements Temporal's grammar pretty closely, but there are a few
differences at the time of writing. It is a specific goal that all differences
should be rooted in what Jiff itself supports, and not in the grammar itself.

* The maximum UTC offset value expressible is `25:59:59` in Jiff, where as in
Temporal it's `23:59:59.999999999`. Jiff supports a slightly bigger maximum
to account for all valid values of POSIX time zone strings. Jiff also lacks
nanosecond precision for UTC offsets, as it's not clear how useful that is in
practice.
* Jiff doesn't support a datetime range as big as Temporal. For example,
in Temporal, `+202024-06-14T17:30[America/New_York]` is valid. But in Jiff,
since the maximum supported year is `9999`, parsing will fail. Jiff's datetime
range may be expanded in the future, but it is a non-goal to match Temporal's
range precisely.
* Jiff doesn't support RFC 9557 calendar annotations because Jiff only supports
the Gregorian calendar.

There is some more [background on Temporal's format] available.

[Temporal ISO 8601 grammar]: https://tc39.es/proposal-temporal/#sec-temporal-iso8601grammar
[RFC 3339]: https://www.rfc-editor.org/rfc/rfc3339
[RFC 9557]: https://www.rfc-editor.org/rfc/rfc9557.html
[ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html
[background on Temporal's format]: https://github.com/tc39/proposal-temporal/issues/2843
*/

use alloc::string::String;

use crate::{
    civil,
    error::Error,
    fmt::Write,
    span::Span,
    tz::{Disambiguation, Offset, OffsetConflict, TimeZoneDatabase},
    SignedDuration, Timestamp, Zoned,
};

mod parser;
mod printer;

/// The default date time parser that we use throughout Jiff.
pub(crate) static DEFAULT_DATETIME_PARSER: DateTimeParser =
    DateTimeParser::new();

/// The default date time printer that we use throughout Jiff.
pub(crate) static DEFAULT_DATETIME_PRINTER: DateTimePrinter =
    DateTimePrinter::new();

/// The default date time parser that we use throughout Jiff.
pub(crate) static DEFAULT_SPAN_PARSER: SpanParser = SpanParser::new();

/// The default date time printer that we use throughout Jiff.
pub(crate) static DEFAULT_SPAN_PRINTER: SpanPrinter = SpanPrinter::new();

/// A parser for Temporal datetimes.
///
/// This parser converts a machine (but also human) readable format of a
/// datetime to the various types found in Jiff: [`Zoned`], [`Timestamp`],
/// [`civil::DateTime`], [`civil::Date`] or [`civil::Time`]. Note that all
/// of those types provide [`FromStr`](core::str::FromStr) implementations
/// that utilize the default configuration of this parser. However, this parser
/// can be configured to behave differently and can also parse directly from
/// a `&[u8]`.
///
/// See the [`fmt::temporal`](crate::fmt::temporal) module documentation for
/// more information on the specific format used.
///
/// # Example
///
/// This example shows how to parse a `Zoned` datetime from a byte string.
/// (That is, `&[u8]` and not a `&str`.)
///
/// ```
/// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
///
/// // A parser can be created in a const context.
/// static PARSER: DateTimeParser = DateTimeParser::new();
///
/// let zdt = PARSER.parse_zoned(b"2024-06-15T07-04[America/New_York]")?;
/// assert_eq!(zdt.datetime(), date(2024, 6, 15).at(7, 0, 0, 0));
/// assert_eq!(zdt.time_zone(), &tz::db().get("America/New_York")?);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Note that an ASCII space instead of the `T` separator is automatically
/// supported too:
///
/// ```
/// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
///
/// // A parser can be created in a const context.
/// static PARSER: DateTimeParser = DateTimeParser::new();
///
/// let zdt = PARSER.parse_zoned(b"2024-06-15 07-04[America/New_York]")?;
/// assert_eq!(zdt.datetime(), date(2024, 6, 15).at(7, 0, 0, 0));
/// assert_eq!(zdt.time_zone(), &tz::db().get("America/New_York")?);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct DateTimeParser {
    p: parser::DateTimeParser,
    offset_conflict: OffsetConflict,
    disambiguation: Disambiguation,
}

impl DateTimeParser {
    /// Create a new Temporal datetime parser with the default configuration.
    #[inline]
    pub const fn new() -> DateTimeParser {
        DateTimeParser {
            p: parser::DateTimeParser::new(),
            offset_conflict: OffsetConflict::Reject,
            disambiguation: Disambiguation::Compatible,
        }
    }

    /// Set the conflict resolution strategy for when an offset in a datetime
    /// string is inconsistent with the time zone.
    ///
    /// See the documentation on [`OffsetConflict`] for more details about the
    /// different strategies one can choose.
    ///
    /// This only applies when parsing [`Zoned`] values.
    ///
    /// The default is [`OffsetConflict::Reject`], which results in an error
    /// whenever parsing a datetime with an offset that is inconsistent with
    /// the time zone.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new()
    ///     .offset_conflict(tz::OffsetConflict::AlwaysOffset);
    ///
    /// let zdt = PARSER.parse_zoned("2024-06-09T07:00-05[America/New_York]")?;
    /// // Notice that the time *and* offset have been corrected. The offset
    /// // given was invalid for `America/New_York` at the given time, so
    /// // it cannot be kept, but the instant returned is equivalent to
    /// // `2024-06-09T07:00-05`. It is just adjusted automatically to be
    /// // correct in the `America/New_York` time zone.
    /// assert_eq!(zdt.datetime(), date(2024, 6, 9).at(8, 0, 0, 0));
    /// assert_eq!(zdt.offset(), tz::offset(-4));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub const fn offset_conflict(
        self,
        strategy: OffsetConflict,
    ) -> DateTimeParser {
        DateTimeParser { offset_conflict: strategy, ..self }
    }

    /// Set the disambiguation strategy for when a datetime falls into a time
    /// zone transition "fold" or "gap."
    ///
    /// The most common manifestation of such time zone transitions is daylight
    /// saving time. In most cases, the transition into daylight saving time
    /// moves the civil time ("the time you see on the clock") ahead one hour.
    /// This is called a "gap" because an hour on the clock is skipped. While
    /// the transition out of daylight saving time moves the civil time back
    /// one hour. This is called a "fold" because an hour on the clock is
    /// repeated.
    ///
    /// In the case of a gap, an ambiguous datetime manifests as a time that
    /// never appears on a clock. (For example, `02:30` on `2024-03-10` in New
    /// York.) In the case of a fold, an ambiguous datetime manifests as a
    /// time that repeats itself. (For example, `01:30` on `2024-11-03` in New
    /// York.) So when a fold occurs, you don't know whether it's the "first"
    /// occurrence of that time or the "second."
    ///
    /// Time zone transitions are not just limited to daylight saving time,
    /// although those are the most common. In other cases, a transition occurs
    /// because of a change in the offset of the time zone itself. (See the
    /// examples below.)
    ///
    /// # Example
    ///
    /// This example shows how to set the disambiguation configuration while
    /// parsing a [`Zoned`] datetime. In this example, we always prefer the
    /// earlier time.
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new()
    ///     .disambiguation(tz::Disambiguation::Earlier);
    ///
    /// let zdt = PARSER.parse_zoned("2024-03-10T02:05[America/New_York]")?;
    /// assert_eq!(zdt.datetime(), date(2024, 3, 10).at(1, 5, 0, 0));
    /// assert_eq!(zdt.offset(), tz::offset(-5));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Example: time zone offset change
    ///
    /// In this example, we explore a time zone offset change in Hawaii that
    /// occurred on `1947-06-08`. Namely, Hawaii went from a `-10:30` offset
    /// to a `-10:00` offset at `02:00`. This results in a 30 minute gap in
    /// civil time.
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz, ToSpan};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new()
    ///     .disambiguation(tz::Disambiguation::Later);
    ///
    /// // 02:05 didn't exist on clocks on 1947-06-08.
    /// let zdt = PARSER.parse_zoned(
    ///     "1947-06-08T02:05[Pacific/Honolulu]",
    /// )?;
    /// // Our parser is configured to select the later time, so we jump to
    /// // 02:35. But if we used `Disambiguation::Earlier`, then we'd get
    /// // 01:35.
    /// assert_eq!(zdt.datetime(), date(1947, 6, 8).at(2, 35, 0, 0));
    /// assert_eq!(zdt.offset(), tz::offset(-10));
    ///
    /// // If we subtract 10 minutes from 02:35, notice that we (correctly)
    /// // jump to 01:55 *and* our offset is corrected to -10:30.
    /// let zdt = zdt.checked_sub(10.minutes())?;
    /// assert_eq!(zdt.datetime(), date(1947, 6, 8).at(1, 55, 0, 0));
    /// assert_eq!(zdt.offset(), tz::offset(-10).saturating_sub(30.minutes()));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub const fn disambiguation(
        self,
        strategy: Disambiguation,
    ) -> DateTimeParser {
        DateTimeParser { disambiguation: strategy, ..self }
    }

    /// Parse a datetime string with a time zone annotation into a [`Zoned`]
    /// value using the system time zone database.
    ///
    /// # Errors
    ///
    /// This returns an error if the datetime string given is invalid or if it
    /// is valid but doesn't fit in the datetime range supported by Jiff.
    ///
    /// The [`DateTimeParser::offset_conflict`] and
    /// [`DateTimeParser::disambiguation`] settings can also influence
    /// whether an error occurs or not. Namely, if [`OffsetConflict::Reject`]
    /// is used (which is the default), then an error occurs when there
    /// is an inconsistency between the offset and the time zone. And if
    /// [`Disambiguation::Reject`] is used, then an error occurs when the civil
    /// time in the string is ambiguous.
    ///
    /// # Example: parsing without an IANA time zone
    ///
    /// Note that when parsing a `Zoned` value, it is required for the datetime
    /// string to contain a time zone annotation in brackets. For example,
    /// this fails to parse even though it refers to a precise instant in time:
    ///
    /// ```
    /// use jiff::fmt::temporal::DateTimeParser;
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// assert!(PARSER.parse_zoned("2024-06-08T07:00-04").is_err());
    /// ```
    ///
    /// While it is better to include a time zone name, if the only thing
    /// that's available is an offset, the offset can be repeated as a time
    /// zone annotation:
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// let zdt = PARSER.parse_zoned("2024-06-08T07:00-04[-04]")?;
    /// assert_eq!(zdt.datetime(), date(2024, 6, 8).at(7, 0, 0, 0));
    /// assert_eq!(zdt.offset(), tz::offset(-4));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Otherwise, if you need to be able to parse something like
    /// `2024-06-08T07:00-04` as-is, you should parse it into an [`Timestamp`]:
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// let timestamp = PARSER.parse_timestamp("2024-06-08T07:00-04")?;
    /// let zdt = timestamp.to_zoned(tz::TimeZone::UTC);
    /// assert_eq!(zdt.datetime(), date(2024, 6, 8).at(11, 0, 0, 0));
    /// assert_eq!(zdt.offset(), tz::offset(0));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_zoned<I: AsRef<[u8]>>(
        &self,
        input: I,
    ) -> Result<Zoned, Error> {
        self.parse_zoned_with(crate::tz::db(), input)
    }

    /// Parse a datetime string with a time zone annotation into a [`Zoned`]
    /// value using the time zone database given.
    ///
    /// # Errors
    ///
    /// This returns an error if the datetime string given is invalid or if it
    /// is valid but doesn't fit in the datetime range supported by Jiff.
    ///
    /// The [`DateTimeParser::offset_conflict`] and
    /// [`DateTimeParser::disambiguation`] settings can also influence
    /// whether an error occurs or not. Namely, if [`OffsetConflict::Reject`]
    /// is used (which is the default), then an error occurs when there
    /// is an inconsistency between the offset and the time zone. And if
    /// [`Disambiguation::Reject`] is used, then an error occurs when the civil
    /// time in the string is ambiguous.
    ///
    /// # Example
    ///
    /// This example demonstrates the utility of this routine by parsing a
    /// datetime using an older copy of the IANA Time Zone Database. This
    /// example leverages the fact that the 2018 copy of `tzdb` preceded
    /// Brazil's announcement that daylight saving time would be abolished.
    /// This meant that datetimes in the future, when parsed with the older
    /// copy of `tzdb`, would still follow the old daylight saving time rules.
    /// But a mere update of `tzdb` would otherwise change the meaning of the
    /// datetime.
    ///
    /// This scenario can come up if one stores datetimes in the future.
    /// This is also why the default offset conflict resolution strategy
    /// is [`OffsetConflict::Reject`], which prevents one from silently
    /// re-interpreting datetimes to a different timestamp.
    ///
    /// ```no_run
    /// use jiff::{fmt::temporal::DateTimeParser, tz::{self, TimeZoneDatabase}};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// // Open a version of tzdb from before Brazil announced its abolition
    /// // of daylight saving time.
    /// let tzdb2018 = TimeZoneDatabase::from_dir("path/to/tzdb-2018b")?;
    /// // Open the system tzdb.
    /// let tzdb = tz::db();
    ///
    /// // Parse the same datetime string with the same parser, but using two
    /// // different versions of tzdb.
    /// let dt = "2020-01-15T12:00[America/Sao_Paulo]";
    /// let zdt2018 = PARSER.parse_zoned_with(&tzdb2018, dt)?;
    /// let zdt = PARSER.parse_zoned_with(tzdb, dt)?;
    ///
    /// // Before DST was abolished, 2020-01-15 was in DST, which corresponded
    /// // to UTC offset -02. Since DST rules applied to datetimes in the
    /// // future, the 2018 version of tzdb would lead one to interpret
    /// // 2020-01-15 as being in DST.
    /// assert_eq!(zdt2018.offset(), tz::offset(-2));
    /// // But DST was abolished in 2019, which means that 2020-01-15 was no
    /// // no longer in DST. So after a tzdb update, the same datetime as above
    /// // now has a different offset.
    /// assert_eq!(zdt.offset(), tz::offset(-3));
    ///
    /// // So if you try to parse a datetime serialized from an older copy of
    /// // tzdb, you'll get an error under the default configuration because
    /// // of `OffsetConflict::Reject`. This would succeed if you parsed it
    /// // using tzdb2018!
    /// assert!(PARSER.parse_zoned_with(tzdb, zdt2018.to_string()).is_err());
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_zoned_with<I: AsRef<[u8]>>(
        &self,
        db: &TimeZoneDatabase,
        input: I,
    ) -> Result<Zoned, Error> {
        let input = input.as_ref();
        let parsed = self.p.parse_temporal_datetime(input)?;
        let dt = parsed.into_full()?;
        let zoned =
            dt.to_zoned(db, self.offset_conflict, self.disambiguation)?;
        Ok(zoned)
    }

    /// Parse a datetime string into a [`Timestamp`].
    ///
    /// The datetime string must correspond to a specific instant in time. This
    /// requires an offset in the datetime string.
    ///
    /// # Errors
    ///
    /// This returns an error if the datetime string given is invalid or if it
    /// is valid but doesn't fit in the datetime range supported by Jiff.
    ///
    /// # Example
    ///
    /// This shows a basic example of parsing an `Timestamp`.
    ///
    /// ```
    /// use jiff::fmt::temporal::DateTimeParser;
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// let timestamp = PARSER.parse_timestamp("2024-03-10T02:05-04")?;
    /// assert_eq!(timestamp.to_string(), "2024-03-10T06:05:00Z");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Example: parsing a timestamp from a datetime with a time zone
    ///
    /// A timestamp can also be parsed fron a time zone aware datetime string.
    /// The time zone is ignored and the offset is always used.
    ///
    /// ```
    /// use jiff::fmt::temporal::DateTimeParser;
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// let timestamp = PARSER.parse_timestamp(
    ///     "2024-03-10T02:05-04[America/New_York]",
    /// )?;
    /// assert_eq!(timestamp.to_string(), "2024-03-10T06:05:00Z");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_timestamp<I: AsRef<[u8]>>(
        &self,
        input: I,
    ) -> Result<Timestamp, Error> {
        let input = input.as_ref();
        let parsed = self.p.parse_temporal_datetime(input)?;
        let dt = parsed.into_full()?;
        let timestamp = dt.to_timestamp()?;
        Ok(timestamp)
    }

    /// Parse a civil datetime string into a [`civil::DateTime`].
    ///
    /// A civil datetime can be parsed from anything that contains a datetime.
    /// For example, a time zone aware string.
    ///
    /// # Errors
    ///
    /// This returns an error if the datetime string given is invalid or if it
    /// is valid but doesn't fit in the datetime range supported by Jiff.
    ///
    /// This also returns an error if a `Z` (Zulu) offset is found, since
    /// interpreting such strings as civil time is usually a bug.
    ///
    /// # Example
    ///
    /// This shows a basic example of parsing a `civil::DateTime`.
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimeParser};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// let datetime = PARSER.parse_datetime("2024-03-10T02:05")?;
    /// assert_eq!(datetime, date(2024, 3, 10).at(2, 5, 0, 0));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Example: parsing fails if a `Z` (Zulu) offset is encountered
    ///
    /// Because parsing a datetime with a `Z` offset and interpreting it as
    /// a civil time is usually a bug, it is forbidden:
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimeParser};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// assert!(PARSER.parse_datetime("2024-03-10T02:05Z").is_err());
    ///
    /// // Note though that -00 and +00 offsets parse successfully.
    /// let datetime = PARSER.parse_datetime("2024-03-10T02:05+00")?;
    /// assert_eq!(datetime, date(2024, 3, 10).at(2, 5, 0, 0));
    /// let datetime = PARSER.parse_datetime("2024-03-10T02:05-00")?;
    /// assert_eq!(datetime, date(2024, 3, 10).at(2, 5, 0, 0));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_datetime<I: AsRef<[u8]>>(
        &self,
        input: I,
    ) -> Result<civil::DateTime, Error> {
        let input = input.as_ref();
        let parsed = self.p.parse_temporal_datetime(input)?;
        let dt = parsed.into_full()?;
        let datetime = dt.to_datetime()?;
        Ok(datetime)
    }

    /// Parse a civil date string into a [`civil::Date`].
    ///
    /// A civil date can be parsed from anything that contains a date. For
    /// example, a time zone aware string.
    ///
    /// # Errors
    ///
    /// This returns an error if the date string given is invalid or if it
    /// is valid but doesn't fit in the date range supported by Jiff.
    ///
    /// This also returns an error if a `Z` (Zulu) offset is found, since
    /// interpreting such strings as civil date or time is usually a bug.
    ///
    /// # Example
    ///
    /// This shows a basic example of parsing a `civil::Date`.
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimeParser};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// let d = PARSER.parse_date("2024-03-10")?;
    /// assert_eq!(d, date(2024, 3, 10));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Example: parsing fails if a `Z` (Zulu) offset is encountered
    ///
    /// Because parsing a date with a `Z` offset and interpreting it as
    /// a civil date or time is usually a bug, it is forbidden:
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimeParser};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// assert!(PARSER.parse_date("2024-03-10T00:00:00Z").is_err());
    ///
    /// // Note though that -00 and +00 offsets parse successfully.
    /// let d = PARSER.parse_date("2024-03-10T00:00:00+00")?;
    /// assert_eq!(d, date(2024, 3, 10));
    /// let d = PARSER.parse_date("2024-03-10T00:00:00-00")?;
    /// assert_eq!(d, date(2024, 3, 10));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_date<I: AsRef<[u8]>>(
        &self,
        input: I,
    ) -> Result<civil::Date, Error> {
        let input = input.as_ref();
        let parsed = self.p.parse_temporal_datetime(input)?;
        let dt = parsed.into_full()?;
        let date = dt.to_date()?;
        Ok(date)
    }

    /// Parse a civil time string into a [`civil::Time`].
    ///
    /// A civil time can be parsed from anything that contains a time.
    /// For example, a time zone aware string.
    ///
    /// # Errors
    ///
    /// This returns an error if the time string given is invalid or if it
    /// is valid but doesn't fit in the time range supported by Jiff.
    ///
    /// This also returns an error if a `Z` (Zulu) offset is found, since
    /// interpreting such strings as civil time is usually a bug.
    ///
    /// # Example
    ///
    /// This shows a basic example of parsing a `civil::Time`.
    ///
    /// ```
    /// use jiff::{civil::time, fmt::temporal::DateTimeParser};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// let t = PARSER.parse_time("02:05")?;
    /// assert_eq!(t, time(2, 5, 0, 0));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Example: parsing fails if a `Z` (Zulu) offset is encountered
    ///
    /// Because parsing a time with a `Z` offset and interpreting it as
    /// a civil time is usually a bug, it is forbidden:
    ///
    /// ```
    /// use jiff::{civil::time, fmt::temporal::DateTimeParser};
    ///
    /// static PARSER: DateTimeParser = DateTimeParser::new();
    ///
    /// assert!(PARSER.parse_time("02:05Z").is_err());
    ///
    /// // Note though that -00 and +00 offsets parse successfully.
    /// let t = PARSER.parse_time("02:05+00")?;
    /// assert_eq!(t, time(2, 5, 0, 0));
    /// let t = PARSER.parse_time("02:05-00")?;
    /// assert_eq!(t, time(2, 5, 0, 0));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_time<I: AsRef<[u8]>>(
        &self,
        input: I,
    ) -> Result<civil::Time, Error> {
        let input = input.as_ref();
        let parsed = self.p.parse_temporal_time(input)?;
        let parsed_time = parsed.into_full()?;
        let time = parsed_time.to_time();
        Ok(time)
    }
}

/// A printer for Temporal datetimes.
///
/// This printer converts an in memory representation of a datetime related
/// type to a machine (but also human) readable format. Using this printer, one
/// can convert [`Zoned`], [`Timestamp`], [`civil::DateTime`], [`civil::Date`]
/// or [`civil::Time`] values to a string. Note that all of those types provide
/// [`Diplay`](core::fmt::Display) implementations that utilize the default
/// configuration of this printer. However, this printer can be configured to
/// behave differently and can also print directly to anything that implements
/// the [`fmt::Write`](Write) trait.
///
/// See the [`fmt::temporal`](crate::fmt::temporal) module documentation for
/// more information on the specific format used. Note that the Temporal
/// datetime parser is strictly more flexible than what is supported by this
/// printer. For example, parsing `2024-06-15T07:00-04[America/New_York]` will
/// work just fine, even though the seconds are omitted. However, this printer
/// provides no way to write a datetime without the second component.
///
/// # Example
///
/// This example shows how to print a `Zoned` value with a space separating
/// the date and time instead of the more standard `T` separator.
///
/// ```
/// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
///
/// // A printer can be created in a const context.
/// const PRINTER: DateTimePrinter = DateTimePrinter::new().separator(b' ');
///
/// let zdt = date(2024, 6, 15).at(7, 0, 0, 123456789).intz("America/New_York")?;
///
/// let mut buf = String::new();
/// // Printing to a `String` can never fail.
/// PRINTER.print_zoned(&zdt, &mut buf).unwrap();
/// assert_eq!(buf, "2024-06-15 07:00:00.123456789-04:00[America/New_York]");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: using adapters with `std::io::Write` and `std::fmt::Write`
///
/// By using the [`StdIoWrite`](super::StdIoWrite) and
/// [`StdFmtWrite`](super::StdFmtWrite) adapters, one can print datetimes
/// directly to implementations of `std::io::Write` and `std::fmt::Write`,
/// respectively. The example below demonstrates writing to anything
/// that implements `std::io::Write`. Similar code can be written for
/// `std::fmt::Write`.
///
/// ```no_run
/// use std::{fs::File, io::{BufWriter, Write}, path::Path};
///
/// use jiff::{civil::date, fmt::{StdIoWrite, temporal::DateTimePrinter}};
///
/// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).intz("America/New_York")?;
///
/// let path = Path::new("/tmp/output");
/// let mut file = BufWriter::new(File::create(path)?);
/// DateTimePrinter::new().print_zoned(&zdt, StdIoWrite(&mut file)).unwrap();
/// file.flush()?;
/// assert_eq!(
///     std::fs::read_to_string(path)?,
///     "2024-06-15T07:00:00-04:00[America/New_York]",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct DateTimePrinter {
    p: printer::DateTimePrinter,
}

impl DateTimePrinter {
    /// Create a new Temporal datetime printer with the default configuration.
    pub const fn new() -> DateTimePrinter {
        DateTimePrinter { p: printer::DateTimePrinter::new() }
    }

    /// Use lowercase for the datetime separator and the `Z` (Zulu) UTC offset.
    ///
    /// This is disabled by default.
    ///
    /// # Example
    ///
    /// This example shows how to print a `Zoned` value with a lowercase
    /// datetime separator.
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new().lowercase(true);
    ///
    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).intz("America/New_York")?;
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// PRINTER.print_zoned(&zdt, &mut buf).unwrap();
    /// assert_eq!(buf, "2024-06-15t07:00:00-04:00[America/New_York]");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub const fn lowercase(mut self, yes: bool) -> DateTimePrinter {
        self.p = self.p.lowercase(yes);
        self
    }

    /// Use the given ASCII character to separate the date and time when
    /// printing [`Zoned`], [`Timestamp`] or [`civil::DateTime`] values.
    ///
    /// This is set to `T` by default.
    ///
    /// # Example
    ///
    /// This example shows how to print a `Zoned` value with a different
    /// datetime separator.
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
    ///
    /// // We use a weird non-standard character here, but typically one would
    /// // use this method with an ASCII space.
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new().separator(b'~');
    ///
    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).intz("America/New_York")?;
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// PRINTER.print_zoned(&zdt, &mut buf).unwrap();
    /// assert_eq!(buf, "2024-06-15~07:00:00-04:00[America/New_York]");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub const fn separator(mut self, ascii_char: u8) -> DateTimePrinter {
        self.p = self.p.separator(ascii_char);
        self
    }

    /// Set the precision to use for formatting the fractional second component
    /// of a time.
    ///
    /// The default is `None`, which will automatically set the precision based
    /// on the value.
    ///
    /// When the precision is set to `N`, you'll always get precisely `N`
    /// digits after a decimal point (unless `N==0`, then no fractional
    /// component is printed), even if they are `0`.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter =
    ///     DateTimePrinter::new().precision(Some(3));
    ///
    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 123_456_789).intz("US/Eastern")?;
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// PRINTER.print_zoned(&zdt, &mut buf).unwrap();
    /// assert_eq!(buf, "2024-06-15T07:00:00.123-04:00[US/Eastern]");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Example: available via formatting machinery
    ///
    /// When formatting datetime types that may contain a fractional second
    /// component, this can be set via Rust's formatting DSL. Specifically,
    /// it corresponds to the [`std::fmt::Formatter::precision`] setting.
    ///
    /// ```
    /// use jiff::civil::date;
    ///
    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 123_000_000).intz("US/Eastern")?;
    /// assert_eq!(
    ///     format!("{zdt:.6}"),
    ///     "2024-06-15T07:00:00.123000-04:00[US/Eastern]",
    /// );
    /// // Precision values greater than 9 are clamped to 9.
    /// assert_eq!(
    ///     format!("{zdt:.300}"),
    ///     "2024-06-15T07:00:00.123000000-04:00[US/Eastern]",
    /// );
    /// // A precision of 0 implies the entire fractional
    /// // component is always truncated.
    /// assert_eq!(
    ///     format!("{zdt:.0}"),
    ///     "2024-06-15T07:00:00-04:00[US/Eastern]",
    /// );
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub const fn precision(
        mut self,
        precision: Option<u8>,
    ) -> DateTimePrinter {
        self.p = self.p.precision(precision);
        self
    }

    /// Format a `Zoned` datetime into a string.
    ///
    /// This is a convenience routine for [`DateTimePrinter::print_zoned`] with
    /// a `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).intz("America/New_York")?;
    /// assert_eq!(
    ///     PRINTER.zoned_to_string(&zdt),
    ///     "2024-06-15T07:00:00-04:00[America/New_York]",
    /// );
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn zoned_to_string(&self, zdt: &Zoned) -> String {
        let mut buf = String::with_capacity(4);
        // OK because writing to `String` never fails.
        self.print_zoned(zdt, &mut buf).unwrap();
        buf
    }

    /// Format a `Timestamp` datetime into a string.
    ///
    /// This will always return an RFC 3339 compatible string with a `Z` or
    /// Zulu offset. Zulu is chosen in accordance with RFC 9557's update to
    /// RFC 3339 that establishes the `-00:00` offset as equivalent to Zulu:
    ///
    /// > If the time in UTC is known, but the offset to local time is
    /// > unknown, this can be represented with an offset of "Z".  (The
    /// > original version of this specification provided -00:00 for this
    /// > purpose, which is not allowed by ISO8601:2000 and therefore is
    /// > less interoperable; Section 3.3 of RFC5322 describes a related
    /// > convention for email, which does not have this problem).  This
    /// > differs semantically from an offset of +00:00, which implies that
    /// > UTC is the preferred reference point for the specified time.
    ///
    /// In other words, both Zulu time and `-00:00` mean "the time in UTC is
    /// known, but the offset to local time is unknown."
    ///
    /// If you need to format an RFC 3339 timestamp with a specific offset,
    /// use [`DateTimePrinter::timestamp_with_offset_to_string`].
    ///
    /// This is a convenience routine for [`DateTimePrinter::print_timestamp`]
    /// with a `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{fmt::temporal::DateTimePrinter, Timestamp};
    ///
    /// let timestamp = Timestamp::new(0, 1)
    ///     .expect("one nanosecond after Unix epoch is always valid");
    /// assert_eq!(
    ///     DateTimePrinter::new().timestamp_to_string(&timestamp),
    ///     "1970-01-01T00:00:00.000000001Z",
    /// );
    /// ```
    pub fn timestamp_to_string(&self, timestamp: &Timestamp) -> String {
        let mut buf = String::with_capacity(4);
        // OK because writing to `String` never fails.
        self.print_timestamp(timestamp, &mut buf).unwrap();
        buf
    }

    /// Format a `Timestamp` datetime into a string with the given offset.
    ///
    /// This will always return an RFC 3339 compatible string with an offset.
    ///
    /// This will never use either `Z` (for Zulu time) or `-00:00` as an
    /// offset. This is because Zulu time (and `-00:00`) mean "the time in UTC
    /// is known, but the offset to local time is unknown." Since this routine
    /// accepts an explicit offset, the offset is known. For example,
    /// `Offset::UTC` will be formatted as `+00:00`.
    ///
    /// To format an RFC 3339 string in Zulu time, use
    /// [`DateTimePrinter::timestamp_to_string`].
    ///
    /// This is a convenience routine for
    /// [`DateTimePrinter::print_timestamp_with_offset`] with a `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{fmt::temporal::DateTimePrinter, tz, Timestamp};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let timestamp = Timestamp::new(0, 1)
    ///     .expect("one nanosecond after Unix epoch is always valid");
    /// assert_eq!(
    ///     PRINTER.timestamp_with_offset_to_string(&timestamp, tz::offset(-5)),
    ///     "1969-12-31T19:00:00.000000001-05:00",
    /// );
    /// ```
    ///
    /// # Example: `Offset::UTC` formats as `+00:00`
    ///
    /// ```
    /// use jiff::{fmt::temporal::DateTimePrinter, tz::Offset, Timestamp};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let timestamp = Timestamp::new(0, 1)
    ///     .expect("one nanosecond after Unix epoch is always valid");
    /// assert_eq!(
    ///     PRINTER.timestamp_with_offset_to_string(&timestamp, Offset::UTC),
    ///     "1970-01-01T00:00:00.000000001+00:00",
    /// );
    /// ```
    pub fn timestamp_with_offset_to_string(
        &self,
        timestamp: &Timestamp,
        offset: Offset,
    ) -> String {
        let mut buf = String::with_capacity(4);
        // OK because writing to `String` never fails.
        self.print_timestamp_with_offset(timestamp, offset, &mut buf).unwrap();
        buf
    }

    /// Format a `civil::DateTime` into a string.
    ///
    /// This is a convenience routine for [`DateTimePrinter::print_datetime`]
    /// with a `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let dt = date(2024, 6, 15).at(7, 0, 0, 0);
    /// assert_eq!(PRINTER.datetime_to_string(&dt), "2024-06-15T07:00:00");
    /// ```
    pub fn datetime_to_string(&self, dt: &civil::DateTime) -> String {
        let mut buf = String::with_capacity(4);
        // OK because writing to `String` never fails.
        self.print_datetime(dt, &mut buf).unwrap();
        buf
    }

    /// Format a `civil::Date` into a string.
    ///
    /// This is a convenience routine for [`DateTimePrinter::print_date`]
    /// with a `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let d = date(2024, 6, 15);
    /// assert_eq!(PRINTER.date_to_string(&d), "2024-06-15");
    /// ```
    pub fn date_to_string(&self, date: &civil::Date) -> String {
        let mut buf = String::with_capacity(4);
        // OK because writing to `String` never fails.
        self.print_date(date, &mut buf).unwrap();
        buf
    }

    /// Format a `civil::Time` into a string.
    ///
    /// This is a convenience routine for [`DateTimePrinter::print_time`]
    /// with a `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::time, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let t = time(7, 0, 0, 0);
    /// assert_eq!(PRINTER.time_to_string(&t), "07:00:00");
    /// ```
    pub fn time_to_string(&self, time: &civil::Time) -> String {
        let mut buf = String::with_capacity(4);
        // OK because writing to `String` never fails.
        self.print_time(time, &mut buf).unwrap();
        buf
    }

    /// Print a `Zoned` datetime to the given writer.
    ///
    /// # Errors
    ///
    /// This only returns an error when writing to the given [`Write`]
    /// implementation would fail. Some such implementations, like for `String`
    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
    /// cases, it would be appropriate to call `unwrap()` on the result.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).intz("America/New_York")?;
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// PRINTER.print_zoned(&zdt, &mut buf).unwrap();
    /// assert_eq!(buf, "2024-06-15T07:00:00-04:00[America/New_York]");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn print_zoned<W: Write>(
        &self,
        zdt: &Zoned,
        wtr: W,
    ) -> Result<(), Error> {
        self.p.print_zoned(zdt, wtr)
    }

    /// Print a `Timestamp` datetime to the given writer.
    ///
    /// This will always write an RFC 3339 compatible string with a `Z` or
    /// Zulu offset. Zulu is chosen in accordance with RFC 9557's update to
    /// RFC 3339 that establishes the `-00:00` offset as equivalent to Zulu:
    ///
    /// > If the time in UTC is known, but the offset to local time is
    /// > unknown, this can be represented with an offset of "Z".  (The
    /// > original version of this specification provided -00:00 for this
    /// > purpose, which is not allowed by ISO8601:2000 and therefore is
    /// > less interoperable; Section 3.3 of RFC5322 describes a related
    /// > convention for email, which does not have this problem).  This
    /// > differs semantically from an offset of +00:00, which implies that
    /// > UTC is the preferred reference point for the specified time.
    ///
    /// In other words, both Zulu time and `-00:00` mean "the time in UTC is
    /// known, but the offset to local time is unknown."
    ///
    /// If you need to write an RFC 3339 timestamp with a specific offset,
    /// use [`DateTimePrinter::print_timestamp_with_offset`].
    ///
    /// # Errors
    ///
    /// This only returns an error when writing to the given [`Write`]
    /// implementation would fail. Some such implementations, like for `String`
    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
    /// cases, it would be appropriate to call `unwrap()` on the result.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{fmt::temporal::DateTimePrinter, Timestamp};
    ///
    /// let timestamp = Timestamp::new(0, 1)
    ///     .expect("one nanosecond after Unix epoch is always valid");
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// DateTimePrinter::new().print_timestamp(&timestamp, &mut buf).unwrap();
    /// assert_eq!(buf, "1970-01-01T00:00:00.000000001Z");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn print_timestamp<W: Write>(
        &self,
        timestamp: &Timestamp,
        wtr: W,
    ) -> Result<(), Error> {
        self.p.print_timestamp(timestamp, None, wtr)
    }

    /// Print a `Timestamp` datetime to the given writer with the given offset.
    ///
    /// This will always write an RFC 3339 compatible string with an offset.
    ///
    /// This will never write either `Z` (for Zulu time) or `-00:00` as an
    /// offset. This is because Zulu time (and `-00:00`) mean "the time in UTC
    /// is known, but the offset to local time is unknown." Since this routine
    /// accepts an explicit offset, the offset is known. For example,
    /// `Offset::UTC` will be formatted as `+00:00`.
    ///
    /// To write an RFC 3339 string in Zulu time, use
    /// [`DateTimePrinter::print_timestamp`].
    ///
    /// # Errors
    ///
    /// This only returns an error when writing to the given [`Write`]
    /// implementation would fail. Some such implementations, like for `String`
    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
    /// cases, it would be appropriate to call `unwrap()` on the result.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{fmt::temporal::DateTimePrinter, tz, Timestamp};
    ///
    /// let timestamp = Timestamp::new(0, 1)
    ///     .expect("one nanosecond after Unix epoch is always valid");
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// DateTimePrinter::new().print_timestamp_with_offset(
    ///     &timestamp,
    ///     tz::offset(-5),
    ///     &mut buf,
    /// ).unwrap();
    /// assert_eq!(buf, "1969-12-31T19:00:00.000000001-05:00");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Example: `Offset::UTC` formats as `+00:00`
    ///
    /// ```
    /// use jiff::{fmt::temporal::DateTimePrinter, tz::Offset, Timestamp};
    ///
    /// let timestamp = Timestamp::new(0, 1)
    ///     .expect("one nanosecond after Unix epoch is always valid");
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// DateTimePrinter::new().print_timestamp_with_offset(
    ///     &timestamp,
    ///     Offset::UTC, // equivalent to `Offset::from_hours(0)`
    ///     &mut buf,
    /// ).unwrap();
    /// assert_eq!(buf, "1970-01-01T00:00:00.000000001+00:00");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn print_timestamp_with_offset<W: Write>(
        &self,
        timestamp: &Timestamp,
        offset: Offset,
        wtr: W,
    ) -> Result<(), Error> {
        self.p.print_timestamp(timestamp, Some(offset), wtr)
    }

    /// Print a `civil::DateTime` to the given writer.
    ///
    /// # Errors
    ///
    /// This only returns an error when writing to the given [`Write`]
    /// implementation would fail. Some such implementations, like for `String`
    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
    /// cases, it would be appropriate to call `unwrap()` on the result.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let d = date(2024, 6, 15).at(7, 0, 0, 0);
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// PRINTER.print_datetime(&d, &mut buf).unwrap();
    /// assert_eq!(buf, "2024-06-15T07:00:00");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn print_datetime<W: Write>(
        &self,
        dt: &civil::DateTime,
        wtr: W,
    ) -> Result<(), Error> {
        self.p.print_datetime(dt, wtr)
    }

    /// Print a `civil::Date` to the given writer.
    ///
    /// # Errors
    ///
    /// This only returns an error when writing to the given [`Write`]
    /// implementation would fail. Some such implementations, like for `String`
    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
    /// cases, it would be appropriate to call `unwrap()` on the result.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let d = date(2024, 6, 15);
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// PRINTER.print_date(&d, &mut buf).unwrap();
    /// assert_eq!(buf, "2024-06-15");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn print_date<W: Write>(
        &self,
        date: &civil::Date,
        wtr: W,
    ) -> Result<(), Error> {
        self.p.print_date(date, wtr)
    }

    /// Print a `civil::Time` to the given writer.
    ///
    /// # Errors
    ///
    /// This only returns an error when writing to the given [`Write`]
    /// implementation would fail. Some such implementations, like for `String`
    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
    /// cases, it would be appropriate to call `unwrap()` on the result.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{civil::time, fmt::temporal::DateTimePrinter};
    ///
    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
    ///
    /// let t = time(7, 0, 0, 0);
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// PRINTER.print_time(&t, &mut buf).unwrap();
    /// assert_eq!(buf, "07:00:00");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn print_time<W: Write>(
        &self,
        time: &civil::Time,
        wtr: W,
    ) -> Result<(), Error> {
        self.p.print_time(time, wtr)
    }
}

/// A parser for Temporal durations.
///
/// Note that in Jiff, a "Temporal duration" is called a "span."
///
/// See the [`fmt::temporal`](crate::fmt::temporal) module documentation for
/// more information on the specific format used.
///
/// # Example
///
/// This example shows how to parse a [`Span`] from a byte string. (That is,
/// `&[u8]` and not a `&str`.)
///
/// ```
/// use jiff::{fmt::temporal::SpanParser, ToSpan};
///
/// // A parser can be created in a const context.
/// static PARSER: SpanParser = SpanParser::new();
///
/// let span = PARSER.parse_span(b"P3y7m25dT7h36m")?;
/// assert_eq!(span, 3.years().months(7).days(25).hours(7).minutes(36));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct SpanParser {
    p: parser::SpanParser,
}

impl SpanParser {
    /// Create a new Temporal datetime printer with the default configuration.
    #[inline]
    pub const fn new() -> SpanParser {
        SpanParser { p: parser::SpanParser::new() }
    }

    /// Parse a span string into a [`Span`] value.
    ///
    /// # Errors
    ///
    /// This returns an error if the span string given is invalid or if it
    /// is valid but doesn't fit in the span range supported by Jiff.
    ///
    /// # Example
    ///
    /// This shows a basic example of using this routine.
    ///
    /// ```
    /// use jiff::{fmt::temporal::SpanParser, ToSpan};
    ///
    /// static PARSER: SpanParser = SpanParser::new();
    ///
    /// let span = PARSER.parse_span(b"PT48m")?;
    /// assert_eq!(span, 48.minutes());
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Note that unless you need to parse a span from a byte string,
    /// at time of writing, there is no other advantage to using this
    /// parser directly. It is likely more convenient to just use the
    /// [`FromStr`](std::str::FromStr) trait implementation on [`Span`]:
    ///
    /// ```
    /// use jiff::{Span, ToSpan};
    ///
    /// let span = "PT48m".parse::<Span>()?;
    /// assert_eq!(span, 48.minutes());
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_span<I: AsRef<[u8]>>(&self, input: I) -> Result<Span, Error> {
        let input = input.as_ref();
        let parsed = self.p.parse_temporal_duration(input)?;
        let span = parsed.into_full()?;
        Ok(span)
    }

    /// Parse an ISO 8601 duration string into a [`SignedDuration`] value.
    ///
    /// # Errors
    ///
    /// This returns an error if the span string given is invalid or if it is
    /// valid but can't be converted to a `SignedDuration`. This can occur
    /// when the parsed time exceeds the minimum and maximum `SignedDuration`
    /// values, or if there are any non-zero units greater than hours.
    ///
    /// # Example
    ///
    /// This shows a basic example of using this routine.
    ///
    /// ```
    /// use jiff::{fmt::temporal::SpanParser, SignedDuration};
    ///
    /// static PARSER: SpanParser = SpanParser::new();
    ///
    /// let duration = PARSER.parse_duration(b"PT48m")?;
    /// assert_eq!(duration, SignedDuration::from_mins(48));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Note that unless you need to parse a span from a byte string,
    /// at time of writing, there is no other advantage to using this
    /// parser directly. It is likely more convenient to just use
    /// the [`FromStr`](std::str::FromStr) trait implementation on
    /// [`SignedDuration`]:
    ///
    /// ```
    /// use jiff::SignedDuration;
    ///
    /// let duration = "PT48m".parse::<SignedDuration>()?;
    /// assert_eq!(duration, SignedDuration::from_mins(48));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_duration<I: AsRef<[u8]>>(
        &self,
        input: I,
    ) -> Result<SignedDuration, Error> {
        let input = input.as_ref();
        let parsed = self.p.parse_signed_duration(input)?;
        let dur = parsed.into_full()?;
        Ok(dur)
    }
}

/// A printer for Temporal durations.
///
/// Note that in Jiff, a "Temporal duration" is called a "span."
///
/// This printer converts an in memory representation of a duration of time
/// to a machine (but also human) readable format. Using this printer,
/// one can convert a [`Span`] to a string. Note that a `Span` provides a
/// [`Display`](std::fmt::Display) trait implementation that utilize the
/// default configuration of this printer. However, this printer can print
/// directly to anything that implements the [`fmt::Write`](Write) trait.
///
/// See the [`fmt::temporal`](crate::fmt::temporal) module documentation for
/// more information on the specific format used.
///
/// # Example
///
/// This is a basic example showing how to print a [`Span`] directly to a
/// `Vec<u8>`.
///
/// ```
/// use jiff::{fmt::temporal::SpanPrinter, ToSpan};
///
/// // A printer can be created in a const context.
/// const PRINTER: SpanPrinter = SpanPrinter::new();
///
/// let span = 48.minutes();
/// let mut buf = vec![];
/// // Printing to a `Vec<u8>` can never fail.
/// PRINTER.print_span(&span, &mut buf).unwrap();
/// assert_eq!(buf, "PT48m".as_bytes());
/// ```
///
/// # Example: using adapters with `std::io::Write` and `std::fmt::Write`
///
/// By using the [`StdIoWrite`](super::StdIoWrite) and
/// [`StdFmtWrite`](super::StdFmtWrite) adapters, one can print spans
/// directly to implementations of `std::io::Write` and `std::fmt::Write`,
/// respectively. The example below demonstrates writing to anything
/// that implements `std::io::Write`. Similar code can be written for
/// `std::fmt::Write`.
///
/// ```no_run
/// use std::{fs::File, io::{BufWriter, Write}, path::Path};
///
/// use jiff::{fmt::{StdIoWrite, temporal::SpanPrinter}, ToSpan};
///
/// let span = 48.minutes();
///
/// let path = Path::new("/tmp/output");
/// let mut file = BufWriter::new(File::create(path)?);
/// SpanPrinter::new().print_span(&span, StdIoWrite(&mut file)).unwrap();
/// file.flush()?;
/// assert_eq!(std::fs::read_to_string(path)?, "PT48m");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct SpanPrinter {
    p: printer::SpanPrinter,
}

impl SpanPrinter {
    /// Create a new Temporal span printer with the default configuration.
    #[inline]
    pub const fn new() -> SpanPrinter {
        SpanPrinter { p: printer::SpanPrinter::new() }
    }

    /// Format a `Span` into a string.
    ///
    /// This is a convenience routine for [`SpanPrinter::print_span`] with
    /// a `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{fmt::temporal::SpanPrinter, ToSpan};
    ///
    /// const PRINTER: SpanPrinter = SpanPrinter::new();
    ///
    /// let span = 3.years().months(5);
    /// assert_eq!(PRINTER.span_to_string(&span), "P3y5m");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn span_to_string(&self, span: &Span) -> String {
        let mut buf = String::with_capacity(4);
        // OK because writing to `String` never fails.
        self.print_span(span, &mut buf).unwrap();
        buf
    }

    /// Format a `SignedDuration` into a string.
    ///
    /// This balances the units of the duration up to at most hours
    /// automatically.
    ///
    /// This is a convenience routine for [`SpanPrinter::print_duration`] with
    /// a `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{fmt::temporal::SpanPrinter, SignedDuration};
    ///
    /// const PRINTER: SpanPrinter = SpanPrinter::new();
    ///
    /// let dur = SignedDuration::new(86_525, 123_000_789);
    /// assert_eq!(PRINTER.duration_to_string(&dur), "PT24h2m5.123000789s");
    /// assert_eq!(PRINTER.duration_to_string(&-dur), "-PT24h2m5.123000789s");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn duration_to_string(&self, duration: &SignedDuration) -> String {
        let mut buf = String::with_capacity(4);
        // OK because writing to `String` never fails.
        self.print_duration(duration, &mut buf).unwrap();
        buf
    }

    /// Print a `Span` to the given writer.
    ///
    /// # Errors
    ///
    /// This only returns an error when writing to the given [`Write`]
    /// implementation would fail. Some such implementations, like for `String`
    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
    /// cases, it would be appropriate to call `unwrap()` on the result.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{fmt::temporal::SpanPrinter, ToSpan};
    ///
    /// const PRINTER: SpanPrinter = SpanPrinter::new();
    ///
    /// let span = 3.years().months(5);
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// PRINTER.print_span(&span, &mut buf).unwrap();
    /// assert_eq!(buf, "P3y5m");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn print_span<W: Write>(
        &self,
        span: &Span,
        wtr: W,
    ) -> Result<(), Error> {
        self.p.print_span(span, wtr)
    }

    /// Print a `SignedDuration` to the given writer.
    ///
    /// This balances the units of the duration up to at most hours
    /// automatically.
    ///
    /// # Errors
    ///
    /// This only returns an error when writing to the given [`Write`]
    /// implementation would fail. Some such implementations, like for `String`
    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
    /// cases, it would be appropriate to call `unwrap()` on the result.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff::{fmt::temporal::SpanPrinter, SignedDuration};
    ///
    /// const PRINTER: SpanPrinter = SpanPrinter::new();
    ///
    /// let dur = SignedDuration::new(86_525, 123_000_789);
    ///
    /// let mut buf = String::new();
    /// // Printing to a `String` can never fail.
    /// PRINTER.print_duration(&dur, &mut buf).unwrap();
    /// assert_eq!(buf, "PT24h2m5.123000789s");
    ///
    /// // Negative durations are supported.
    /// buf.clear();
    /// PRINTER.print_duration(&-dur, &mut buf).unwrap();
    /// assert_eq!(buf, "-PT24h2m5.123000789s");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn print_duration<W: Write>(
        &self,
        duration: &SignedDuration,
        wtr: W,
    ) -> Result<(), Error> {
        self.p.print_duration(duration, wtr)
    }
}

#[cfg(test)]
mod tests {
    use alloc::string::ToString;

    use crate::Unit;

    use super::*;

    // This test ensures that strings like `2024-07-15+02` fail to parse.
    // Note though that `2024-07-15[America/New_York]` is okay!
    #[test]
    fn err_temporal_datetime_offset() {
        insta::assert_snapshot!(
            DateTimeParser::new().parse_date(b"2024-07-15+02").unwrap_err(),
            @r###"parsed value '2024-07-15', but unparsed input "+02" remains (expected no unparsed input)"###,
        );
        insta::assert_snapshot!(
            DateTimeParser::new().parse_date(b"2024-07-15-02").unwrap_err(),
            @r###"parsed value '2024-07-15', but unparsed input "-02" remains (expected no unparsed input)"###,
        );
    }

    #[test]
    fn year_zero() {
        insta::assert_snapshot!(
            DateTimeParser::new().parse_date("0000-01-01").unwrap(),
            @"0000-01-01",
        );
        insta::assert_snapshot!(
            DateTimeParser::new().parse_date("+000000-01-01").unwrap(),
            @"0000-01-01",
        );
        insta::assert_snapshot!(
            DateTimeParser::new().parse_date("-000000-01-01").unwrap_err(),
            @r###"failed to parse year in date "-000000-01-01": year zero must be written without a sign or a positive sign, but not a negative sign"###,
        );
    }

    // Regression test for: https://github.com/BurntSushi/jiff/issues/59
    #[test]
    fn fractional_duration_roundtrip() {
        let span1: Span = "Pt843517081,1H".parse().unwrap();
        let span2: Span = span1.to_string().parse().unwrap();
        assert_eq!(
            span1.total(Unit::Hour).unwrap(),
            span2.total(Unit::Hour).unwrap()
        );
    }
}