Debian Codegraph @

debian/rust-vendor/jiff/COMPARE.md

raw
1 # Comparison with other Rust datetime crates
2
3 This document is meant to be a comparison between Jiff and each of the other
4 prominent open source datetime libraries for Rust. If you feel like there is a
5 library missing from this list, please file an issue about it. I would prefer
6 to only add libraries to this list that are being used in production or have a
7 substantial number of users.
8
9 The goal of this document is to be as _descriptive_ and _substantively
10 complete_ as possible. For example, "Chrono has a better API design than Jiff"
11 would be a pretty vague value judgment that someone could easily disagree with.
12 But, "Chrono allows using a zone-aware datetime type that is `Copy` while Jiff
13 does not" would be a factual comparison that someone might use to _support_ an
14 opinion that Chrono's API design is better than Jiff's. In other words, this
15 document should provide the "facts of comparison" but refrain from assigning
16 value judgments.
17
18 In terms of completeness, it is probably not realistic to expect 100%
19 completion here. We aren't hunting for Korok Seeds. Instead, this document
20 aims for _substantive_ completion. That is, if there's a point of difference
21 between Jiff and another library that would likely influence someone's decision
22 of which library to use, and can be articulated descriptively, then it should
23 probably be in this document.
24
25 The current status of this document is that it is both _incomplete_ and
26 _biased_. That is, this first draft was written by the author of Jiff without
27 any input from other crate maintainers. (To other crate maintainers: I welcome
28 feedback. Even if it's just filing an issue.)
29
30 Note that this document contains many code snippets. They can be tested with
31 `cargo test --doc _documentation::comparison` from the root of this repository.
32
33 ## [`chrono`](https://docs.rs/chrono) (v0.4.38)
34
35 Chrono is a Rust datetime library that provides a time zone aware datetime
36 type.
37
38 For the following comparisons, a `Cargo.toml` with the following dependencies
39 should be able to run any of the programs in this section:
40
41 ```toml
42 anyhow = "1.0.81"
43 chrono = "0.4.38"
44 chrono-tz = { version = "0.9.0", features = ["serde"] }
45 jiff = { version = "0.2.0", features = ["serde"] }
46 serde = "1.0.203"
47 serde_json = "1.0.117"
48 tzfile = "0.1.3"
49 ```
50
51 ### Time zone database integration
52
53 Jiff gives you automatic integration with your copy of the Time Zone Database.
54 On Unix, it's usually found at `/usr/share/zoneinfo`. On Windows, since there
55 is no canonical location, Jiff will depend on `jiff-tzdb` by default, which
56 will embed the entire database into your binary. Jiff hides these details from
57 you. For example, to convert a civil time into an absolute time in a particular
58 time zone:
59
60 ```rust
61 use jiff::civil::date;
62
63 fn main() -> anyhow::Result<()> {
64 let zdt = date(2024, 6, 30).at(9, 46, 0, 0).in_tz("America/New_York")?;
65 assert_eq!(zdt.to_string(), "2024-06-30T09:46:00-04:00[America/New_York]");
66 Ok(())
67 }
68 ```
69
70 For Chrono, one recommended option is to use the
71 [`chrono-tz`](https://docs.rs/chrono-tz) crate:
72
73 ```rust
74 use anyhow::Context;
75 use chrono::TimeZone;
76 use chrono_tz::America::New_York;
77
78 fn main() -> anyhow::Result<()> {
79 let zdt = New_York.with_ymd_and_hms(2024, 6, 30, 9, 46, 0)
80 .single()
81 .context("invalid naive time")?;
82 assert_eq!(zdt.to_string(), "2024-06-30 09:46:00 EDT");
83 Ok(())
84 }
85 ```
86
87 `chrono-tz` works by embedding an entire copy of the Time Zone Database into
88 your binary, where each time zone is represented as a Rust value that can be
89 imported via `use`. A disadvantage of this approach is that you're reliant on
90 `chrono-tz` updates to get the most recent time zone information. An advantage
91 of this approach is that you never need to worry about an end user's system
92 state. Another advantage is that this allows a `TimeZone` trait implementation
93 to be `Copy` via a `&Tz`, and that in turn allows a `chrono::DateTime` to be
94 `Copy`. In contrast, in Jiff, a `TimeZone` is never `Copy`. Since a `Zoned`
95 embeds a `TimeZone`, a `Zoned` is never `Copy` either.
96
97 Another recommended option is the [`tzfile`](https://docs.rs/tzfile) crate.
98 Unlike `chrono-tz`, the `tzfile` crate will try to read time zone data from
99 your system's copy of the Time Zone Database.
100
101 ```rust
102 use anyhow::Context;
103 use chrono::TimeZone;
104 use tzfile::Tz;
105
106 #[cfg(unix)]
107 fn main() -> anyhow::Result<()> {
108 let tz = Tz::named("America/New_York")?;
109 let zdt = (&tz).with_ymd_and_hms(2024, 6, 30, 9, 46, 0)
110 .single()
111 .context("invalid naive time")?;
112 assert_eq!(zdt.to_string(), "2024-06-30 09:46:00 EDT");
113 Ok(())
114 }
115
116 // `tzfile` exposes a platform specific API, which means
117 // users of the crate have to deal with platform differences
118 // themselves.
119 #[cfg(not(unix))]
120 fn main() -> anyhow::Result<()> {
121 Ok(())
122 }
123 ```
124
125 Note though that at time of writing (2024-07-11), `tzfile::Tz::named` will
126 read and parse the corresponding time zone rules from disk on every call.
127 Conversely, in Jiff, all time zone lookups by name are cached. This may or may
128 not matter for your use case.
129
130 ### Jiff losslessly roundtrips time zone aware datetimes
131
132 In Jiff, with `serde` support enabled, one can serialize and deserialize a
133 `Zoned` value losslessly. This means that, after deserialization, you can
134 expect it to still perform DST arithmetic:
135
136 ```rust
137 use jiff::{civil::date, ToSpan, Zoned};
138
139 fn main() -> anyhow::Result<()> {
140 let zdt = date(2024, 3, 10).at(1, 59, 59, 0).in_tz("America/New_York")?;
141
142 let json = serde_json::to_string_pretty(&zdt)?;
143 assert_eq!(json, "\"2024-03-10T01:59:59-05:00[America/New_York]\"");
144
145 let got: Zoned = serde_json::from_str(&json)?;
146 assert_eq!(got.to_string(), "2024-03-10T01:59:59-05:00[America/New_York]");
147 let next = got.checked_add(1.minute())?;
148 assert_eq!(next.to_string(), "2024-03-10T03:00:59-04:00[America/New_York]");
149
150 Ok(())
151 }
152 ```
153
154 Notice that when we add a minute, it jumps to `03:00` civil time because of the
155 transition into daylight saving time in my selected time zone. Notice also the
156 offset change from `-05` to `-04`.
157
158 Compare this with Chrono which also supports `serde`, but not with `chrono-tz`
159 or `tzfile`. One option is to use its `Local` implementation of its `TimeZone`
160 trait:
161
162 ```rust,no_run
163 use anyhow::Context;
164 use chrono::{DateTime, FixedOffset, Local, TimeDelta, TimeZone};
165
166 fn main() -> anyhow::Result<()> {
167 let zdt = Local.with_ymd_and_hms(2024, 3, 10, 1, 59, 59)
168 .single()
169 .context("invalid naive time")?;
170
171 let json = serde_json::to_string_pretty(&zdt)?;
172 // Chrono only serializes the offset, which makes lossless
173 // deserialization impossible. Chrono loses the time zone
174 // information.
175 assert_eq!(json, "\"2024-03-10T01:59:59-05:00\"");
176
177 // The serialized datetime has no time zone information,
178 // so unless there is some out-of-band information saying
179 // what its time zone is, we're forced to use a fixed offset:
180 let got: DateTime<FixedOffset> = serde_json::from_str(&json)?;
181 assert_eq!(got.to_string(), "2024-03-10 01:59:59 -05:00");
182 let next = got.checked_add_signed(TimeDelta::minutes(1))
183 .context("arithmetic failed")?;
184 // This is correct for fixed offset, but it's no longer
185 // DST aware.
186 assert_eq!(next.to_string(), "2024-03-10 02:00:59 -05:00");
187
188 // We could deserialize into a `DateTime<Local>`, but this
189 // requires knowing that the time zone of the datetime matches
190 // local time zone. Which you might know. But you might not.
191 let got: DateTime<Local> = serde_json::from_str(&json)?;
192 assert_eq!(got.to_string(), "2024-03-10 01:59:59 -05:00");
193 let next = got.checked_add_signed(TimeDelta::minutes(1))
194 .context("arithmetic failed")?;
195 assert_eq!(next.to_string(), "2024-03-10 03:00:59 -04:00");
196
197 Ok(())
198 }
199 ```
200
201 Or, if you have a `Tz` from `chrono-tz`. But in this case, since `chrono-tz`
202 doesn't support Serde, you have to convert to a `DateTime<FixedOffset>`. Like
203 above, you'll lose DST safe arithmetic after deserialization:
204
205 ```rust
206 use anyhow::Context;
207 use chrono::{DateTime, FixedOffset, TimeDelta, TimeZone};
208 use chrono_tz::America::New_York;
209
210 fn main() -> anyhow::Result<()> {
211 let zdt = New_York.with_ymd_and_hms(2024, 3, 10, 1, 59, 59)
212 .single()
213 .context("invalid naive time")?;
214
215 let json = serde_json::to_string_pretty(&zdt.fixed_offset())?;
216 // Chrono only serializes the offset, which makes lossless
217 // deserialization impossible. Chrono loses the time zone
218 // information.
219 assert_eq!(json, "\"2024-03-10T01:59:59-05:00\"");
220
221 // The serialized datetime has no time zone information,
222 // so unless there is some out-of-band information saying
223 // what its time zone is, we're forced to use a fixed offset:
224 let got: DateTime<FixedOffset> = serde_json::from_str(&json)?;
225 assert_eq!(got.to_string(), "2024-03-10 01:59:59 -05:00");
226 let next = got.checked_add_signed(TimeDelta::minutes(1))
227 .context("arithmetic failed")?;
228 // This is correct for fixed offset, but it's no longer
229 // DST aware.
230 assert_eq!(next.to_string(), "2024-03-10 02:00:59 -05:00");
231
232 Ok(())
233 }
234 ```
235
236 The main way to solve this problem (and is how `java.time`, Temporal and Jiff
237 solve it), is by supporting [RFC 9557]. Otherwise, the only way to fully
238 capture Jiff's functionality in Chrono is to define a custom serialization
239 format that includes the instant, the time zone identifier *and* the offset.
240 (The offset is used for conflict resolution when deserializing datetimes made
241 in the future for which their offset has changed due to changes in the time
242 zone database.)
243
244 [RFC 9557]: https://datatracker.ietf.org/doc/rfc9557/
245
246 ### Jiff provides support for zone aware calendar arithmetic
247
248 With Jiff, you can add non-uniform units like days to time zone aware datetimes,
249 and get non-uniform units like days as a representation of a span between
250 datetimes. And they agree on the results.
251
252 ```rust
253 use jiff::{civil::date, ToSpan, Unit};
254
255 fn main() -> anyhow::Result<()> {
256 let zdt1 = date(2024, 3, 9).at(21, 0, 0, 0).in_tz("America/New_York")?;
257 let zdt2 = zdt1.checked_add(1.day())?;
258
259 // Even though 2 o'clock didn't occur on 2024-03-10, adding 1 day
260 // returns the same civil time the next day.
261 assert_eq!(zdt2.to_string(), "2024-03-10T21:00:00-04:00[America/New_York]");
262 // The span of time is 23 hours:
263 assert_eq!(&zdt2 - &zdt1, 23.hours().fieldwise());
264 // But if you ask for the span in units of days, you get exactly 1:
265 assert_eq!(zdt1.until((Unit::Day, &zdt2))?, 1.day().fieldwise());
266
267 Ok(())
268 }
269 ```
270
271 This is important and difficult to get right because some days are only 23
272 hours long (typically the day of the year where DST starts) and some days are
273 25 hours long (typically the day of the year where DST ends). With Jiff, you
274 can seamlessly go back-and-forth between calendar units and clock units without
275 worrying about whether "day" will be interpreted differently.
276
277 Chrono has some support for this. Namely, it can add units of days in a time
278 zone aware fashion, but it cannot produce spans of time involving days between
279 two zone aware datetimes that is consistent with adding days.
280
281 ```rust
282 use anyhow::Context;
283 use chrono::{Days, TimeDelta, TimeZone};
284 use chrono_tz::America::New_York;
285
286 fn main() -> anyhow::Result<()> {
287 let zdt1 = New_York.with_ymd_and_hms(2024, 3, 9, 21, 0, 0)
288 .single()
289 .context("invalid naive time")?;
290
291 // Adding 1 day via TimeDelta leads to a result that is
292 // 24 hours later, including the gap at 2am on 2024-03-10.
293 // As a result, you get a different civil time, which is
294 // usually not what is intended.
295 let zdt2 = zdt1.checked_add_signed(TimeDelta::days(1))
296 .context("adding a time delta failed")?;
297 assert_eq!(zdt2.to_string(), "2024-03-10 22:00:00 EDT");
298
299 // However, Chrono does expose a separate API for adding
300 // units of days specifically. This does get you the
301 // correct result.
302 let zdt2 = zdt1.checked_add_days(Days::new(1))
303 .context("adding days failed")?;
304 assert_eq!(zdt2.to_string(), "2024-03-10 21:00:00 EDT");
305
306 // The only way to compute a duration between two datetimes
307 // in Chrono is with a `TimeDelta`:
308 let delta = zdt2.signed_duration_since(&zdt1);
309 // And since `TimeDelta` assumes all days are exactly 24
310 // hours long, you get a result of `0` days. If this were
311 // a fold, the number of days would be `1`, but you'd also
312 // have a number of hours equal to `1`.
313 assert_eq!(delta.num_days(), 0);
314
315 Ok(())
316 }
317 ```
318
319 ### Jiff losslessly roundtrips durations
320
321 Jiff implements something close to ISO 8601 to provide lossless serialization
322 and deserialization of its `Span` type. A `Span` covers both calendar and clock
323 units.
324
325 ```rust
326 use jiff::{Span, ToSpan};
327
328 fn main() -> anyhow::Result<()> {
329 let span = 5.years().months(2).days(1).hours(20);
330 let json = serde_json::to_string_pretty(&span)?;
331 assert_eq!(json, "\"P5Y2M1DT20H\"");
332
333 let got: Span = serde_json::from_str(&json)?;
334 assert_eq!(got, span.fieldwise());
335
336 Ok(())
337 }
338 ```
339
340 Chrono [does not currently have Serde support for its duration type][serde-duration].
341
342 [serde-duration]: https://github.com/chronotope/chrono/issues/117
343
344 ### Jiff supports dealing with gaps in civil time
345
346 A gap in civil time most typically occurs when a particular region enters
347 daylight saving time. When this happens, some time on the clocks in that region
348 is skipped. It never appears. (A fold happens when the clocks are rolled back,
349 usually when leaving daylight saving time. In this case, some time on the clock
350 is repeated.)
351
352 Jiff supports automatically selecting a "reasonable" choice in either case
353 via its "compatible" strategy (as specified by [RFC 5545]).
354
355 ```rust
356 use jiff::Zoned;
357
358 fn main() -> anyhow::Result<()> {
359 // This is a gap. The default strategy takes the time after the gap.
360 let zdt: Zoned = "2024-03-10 02:30[America/New_York]".parse()?;
361 assert_eq!(zdt.to_string(), "2024-03-10T03:30:00-04:00[America/New_York]");
362
363 // This is a fold. The default strategy takes the time before the fold.
364 let zdt: Zoned = "2024-11-03 01:30[America/New_York]".parse()?;
365 // The time after the fold would be identical,
366 // except the offset would be -05.
367 assert_eq!(zdt.to_string(), "2024-11-03T01:30:00-04:00[America/New_York]");
368
369 Ok(())
370 }
371 ```
372
373 Jiff also exposes all information available with respect to ambiguous civil
374 datetimes via `tz::AmbiguousZoned`, `tz::AmbiguousTimestamp` and
375 `tz::AmbiguousOffset`. This enables callers to implement whatever strategy
376 they want.
377
378 While Chrono will let you deal with folds, it returns `MappedLocalTime::None`
379 in the case of a gap with no additional information. So there's really nothing
380 else you can conveniently do in this case except return an error:
381
382 ```rust
383 use anyhow::Context;
384 use chrono::{offset::MappedLocalTime, TimeZone};
385 use chrono_tz::America::New_York;
386
387 fn main() -> anyhow::Result<()> {
388 // For gaps, Chrono exposes no additional information.
389 let mapped = New_York.with_ymd_and_hms(2024, 3, 10, 2, 30, 0);
390 assert_eq!(mapped, MappedLocalTime::None);
391
392 // For folds, Chrono gives you the two choices.
393 // This is approximately equivalent to what Jiff exposes
394 // in the case of a fold.
395 let zdt = New_York.with_ymd_and_hms(2024, 11, 3, 1, 30, 0)
396 .earliest()
397 .context("invalid datetime")?;
398 assert_eq!(zdt.to_string(), "2024-11-03 01:30:00 EDT");
399
400 Ok(())
401 }
402 ```
403
404 [RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545
405
406 ### Jiff supports rounding durations
407
408 In Jiff, one can round the duration computed between two datetimes:
409
410 ```rust
411 use jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDifference};
412
413 fn main() -> anyhow::Result<()> {
414 let zdt1 = date(2001, 11, 18).at(8, 30, 0, 0).in_tz("America/New_York")?;
415 let zdt2 = date(2024, 7, 11).at(22, 38, 0, 0).in_tz("America/New_York")?;
416
417 let round_options = ZonedDifference::new(&zdt2)
418 .largest(Unit::Year)
419 .smallest(Unit::Day)
420 .mode(RoundMode::HalfExpand);
421 let span = zdt1.until(round_options)?;
422 assert_eq!(span.fieldwise(), 22.years().months(7).days(24));
423
424 Ok(())
425 }
426 ```
427
428 While Chrono supports rounding datetimes themselves via its
429 `chrono::duration::DurationRound` trait, it does not support rounding durations
430 themselves. Indeed, its principle duration type, `TimeDelta`, is an "absolute"
431 duration like `std::time::Duration` (except that it is signed). It doesn't keep
432 track of individual units like Jiff does. Instead, everything gets normalized
433 into a 96-bit integer number of nanoseconds. With this representation, it is
434 impossible to do DST safe rounding to non-uniform units like days.
435
436 ### Jiff supports zone-aware rounding of durations
437
438 Jiff's duration rounding is time zone aware. For example, if you're rounding to
439 a number of days, it knows to round 11.5 hours up to 1 day on days with gaps,
440 and round 12 hours down to 0 days on days with folds. The only requirement
441 is that we provide a reference datetime with which to interpret the span.
442
443 ```rust
444 use jiff::{civil::date, SpanRound, ToSpan, Unit};
445
446 fn main() -> anyhow::Result<()> {
447 let gapday = date(2024, 3, 10).in_tz("America/New_York")?;
448 let foldday = date(2024, 11, 3).in_tz("America/New_York")?;
449
450 let span1 = 11.hours().minutes(30);
451 let span2 = span1.round(
452 SpanRound::new().smallest(Unit::Day).relative(&gapday),
453 )?;
454 // rounds up, even though on a normal day 11.5 hours would round down.
455 assert_eq!(span2, 1.day().fieldwise());
456
457 let span1 = 12.hours();
458 let span2 = span1.round(
459 SpanRound::new().smallest(Unit::Day).relative(&foldday),
460 )?;
461 // rounds down, even though on a normal day 12 hours would round up.
462 assert_eq!(span2, 0.days().fieldwise());
463
464 Ok(())
465 }
466 ```
467
468 As with the previous section, Chrono does not support rounding durations or
469 rounding units like `Days` with respect to a reference datetime.
470
471 ### Jiff supports re-balancing durations
472
473 This example is like the one above, except we choose a smaller "largest" unit:
474
475 ```rust
476 use jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDifference};
477
478 fn main() -> anyhow::Result<()> {
479 let zdt1 = date(2001, 11, 18).at(8, 30, 0, 0).in_tz("America/New_York")?;
480 let zdt2 = date(2024, 7, 11).at(22, 38, 0, 0).in_tz("America/New_York")?;
481
482 let round_options = ZonedDifference::new(&zdt2)
483 .largest(Unit::Month)
484 .smallest(Unit::Day)
485 .mode(RoundMode::HalfExpand);
486 let span = zdt1.until(round_options)?;
487 assert_eq!(span, 271.months().days(24).fieldwise());
488
489 Ok(())
490 }
491 ```
492
493 ### Jiff supports getting the `nth` weekday from the current date
494
495 ```rust
496 use jiff::civil::{date, Weekday};
497
498 fn main() -> anyhow::Result<()> {
499 let zdt = date(2024, 7, 11).at(22, 59, 0, 0).in_tz("America/New_York")?;
500 assert_eq!(zdt.weekday(), Weekday::Thursday);
501
502 let next_tuesday = zdt.nth_weekday(1, Weekday::Tuesday)?;
503 assert_eq!(
504 next_tuesday.to_string(),
505 "2024-07-16T22:59:00-04:00[America/New_York]",
506 );
507
508 Ok(())
509 }
510 ```
511
512 Chrono does have `NaiveDate::from_weekday_of_month_opt`, but it only counts
513 the number of weekdays for a particular month. (The Jiff equivalent is
514 `nth_weekday_of_month`.) Moreover, Chrono's method is only available on naive
515 dates and not zone aware datetimes.
516
517 ### Jiff supports detecting time zone offset conflicts
518
519 One of the problems with storing datetimes in the future is that time
520 zone rules can change. For example, if you stored the zone aware datetime
521 `2020-01-15T12:00-02[America/Sao_Paulo]` in 2018, then it would be considered
522 to be in daylight saving time with an offset of `-2`. However, in 2019,
523 daylight saving time was abolished in this time zone, which renders the
524 datetime invalid because its offset *should* be `-3`.
525
526 Jiff can detect these sorts of conflicts and will actually return a parse error
527 by default. We exemplify this by creating and serializing a zoned datetime from
528 an old copy of the Time Zone Database, and then try to parse it back using our
529 system's current copy of the Time Zone Database. (This also demonstrate's Jiff
530 support for using multiple copies of the Time Zone Database simultaneously.
531 But the main point here is to simulate the process of "serialize datetime,
532 time zone rules change, deserialize datetime.")
533
534 ```rust,no_run
535 use jiff::{fmt::temporal::DateTimeParser, tz::{self, TimeZoneDatabase}};
536
537 // We use a custom parser with a default configuration because we need
538 // to ask the parser to use a different time zone database than the
539 // default. This can't be done via the nice `"...".parse()` API one
540 // would typically use.
541 static PARSER: DateTimeParser = DateTimeParser::new();
542
543 fn main() -> anyhow::Result<()> {
544 // Open a version of tzdb from before Brazil announced its abolition
545 // of daylight saving time.
546 let tzdb2018 = TimeZoneDatabase::from_dir("path/to/tzdb-2018b")?;
547 // Open the system tzdb.
548 let tzdb = tz::db();
549
550 // Parse the same datetime string with the same parser, but using two
551 // different versions of tzdb.
552 let dt = "2020-01-15T12:00[America/Sao_Paulo]";
553 let zdt2018 = PARSER.parse_zoned_with(&tzdb2018, dt)?;
554 let zdt = PARSER.parse_zoned_with(tzdb, dt)?;
555
556 // Before DST was abolished, 2020-01-15 was in DST, which corresponded
557 // to UTC offset -02. Since DST rules applied to datetimes in the
558 // future, the 2018 version of tzdb would lead one to interpret
559 // 2020-01-15 as being in DST.
560 assert_eq!(zdt2018.offset(), tz::offset(-2));
561 // But DST was abolished in 2019, which means that 2020-01-15 was no
562 // no longer in DST. So after a tzdb update, the same datetime as above
563 // now has a different offset.
564 assert_eq!(zdt.offset(), tz::offset(-3));
565
566 // So if you try to parse a datetime serialized from an older copy of
567 // tzdb with a new copy of tzdb, you'll get an error under the default
568 // configuration because of `OffsetConflict::Reject`. This would succeed if
569 // you parsed it using tzdb2018!
570 assert!(PARSER.parse_zoned_with(tzdb, zdt2018.to_string()).is_err());
571
572 Ok(())
573 }
574 ```
575
576 With Chrono, this sort of checking isn't possible in the first place because
577 it doesn't support an interchange format that includes the IANA time zone
578 identifier.
579
580 ### Jiff supports adding durations with calendar units
581
582 Since `Span` is Jiff's single duration type that combines calendar and clock
583 units, one can freely add them together. The only requirement is that if a span
584 has calendar units, you need to provide a reference date. (Because 1 month from
585 April 1 is shorter than 1 month from May 1.)
586
587 ```rust
588 use jiff::{civil::date, ToSpan};
589
590 fn main() -> anyhow::Result<()> {
591 let span1 = 2.years().months(4).days(25).hours(23);
592 let span2 = 3.hours();
593 let span3 = span1.checked_add((span2, date(2024, 1, 1)))?;
594 assert_eq!(span3.fieldwise(), 2.years().months(4).days(26).hours(2));
595
596 Ok(())
597 }
598 ```
599
600 While Chrono has types like `Months` and `Days`, there's no way to combine
601 them into one, and Chrono does not provide operations on both at the same time.
602
603 ### Jiff supports zone-aware re-balancing of durations
604
605 If you have a span of `1.day()` and want to convert it to hours, then that
606 calculation depends on how long the day is. If you provide a civil date as
607 a relative reference point, then Jiff assumes the day is always 24 hours long:
608
609 ```rust
610 use jiff::{civil, SpanRound, ToSpan, Unit};
611
612 fn main() -> anyhow::Result<()> {
613 let relative = civil::date(2024, 4, 1);
614 let span1 = 1.day();
615 let span2 = span1.round(
616 SpanRound::new().largest(Unit::Hour).relative(relative),
617 )?;
618 assert_eq!(span2, 24.hours().fieldwise());
619
620 Ok(())
621 }
622 ```
623
624 But if a reference date is provided with a time zone, then the re-balancing is
625 DST safe:
626
627 ```rust
628 use jiff::{civil::date, SpanRound, ToSpan, Unit};
629
630 fn main() -> anyhow::Result<()> {
631 // In the case of a gap (typically transitioning in DST):
632 let zdt = date(2024, 3, 9).at(21, 0, 0, 0).in_tz("America/New_York")?;
633 let span1 = 1.day();
634 let span2 = span1.round(
635 SpanRound::new().largest(Unit::Hour).relative(&zdt)
636 )?;
637 assert_eq!(span2, 23.hours().fieldwise());
638
639 // In the case of a fold (typically transitioning out of DST):
640 let zdt = date(2024, 11, 2).at(21, 0, 0, 0).in_tz("America/New_York")?;
641 let span1 = 1.day();
642 let span2 = span1.round(
643 SpanRound::new().largest(Unit::Hour).relative(&zdt)
644 )?;
645 assert_eq!(span2, 25.hours().fieldwise());
646
647 Ok(())
648 }
649 ```
650
651 ### Jiff is generally faster than Chrono
652
653 There are some cases where Chrono is faster than Jiff, but Jiff should
654 generally be competitive for equivalent operations. It's generally not
655 possible for Chrono or Jiff to always be faster than the other, since
656 they each use different representations for fundamental types. This in turn
657 makes some operations faster and others slower, depending on what you're
658 trying to do. With that said, Jiff is uniformly faster than Chrono when it
659 comes to printing and parsing.
660
661 ```text
662 $ cd bench
663 $ cargo bench -- --save-baseline base
664 [.. snip ..]
665 $ critcmp base -g '(.*)/(?:jiff|chrono)$'
666 group baseline//chrono baseline//jiff
667 ----- ---------------- --------------
668 civil_datetime/add_days/diffyear/duration 1.00 8.5±0.08ns ? ?/sec 1.56 13.3±0.15ns ? ?/sec
669 civil_datetime/add_days/diffyear/span 1.00 23.9±0.13ns ? ?/sec
670 civil_datetime/add_days/sameyear/duration 1.00 6.8±0.05ns ? ?/sec 1.96 13.3±0.17ns ? ?/sec
671 civil_datetime/add_days/sameyear/span 1.00 23.8±0.13ns ? ?/sec
672 civil_datetime/to_timestamp_static/bundled 2.05 22.3±0.24ns ? ?/sec 1.00 10.9±0.14ns ? ?/sec
673 civil_datetime/to_timestamp_static/zoneinfo 1.53 16.2±0.15ns ? ?/sec 1.00 10.6±0.09ns ? ?/sec
674 civil_datetime/to_timestamp_tzdb_lookup/bundled 1.00 32.0±0.15ns ? ?/sec
675 civil_datetime/to_timestamp_tzdb_lookup/zoneinfo 45.85 1919.7±6.17ns ? ?/sec 1.00 41.9±0.15ns ? ?/sec
676 date/add_days/diffyear/duration 1.00 5.8±0.05ns ? ?/sec 1.12 6.5±0.04ns ? ?/sec
677 date/add_days/diffyear/span 1.00 6.5±0.04ns ? ?/sec
678 date/add_days/one/duration 1.00 2.1±0.02ns ? ?/sec 2.55 5.4±0.05ns ? ?/sec
679 date/add_days/one/span 1.00 5.8±0.02ns ? ?/sec
680 date/add_days/sameyear/duration 1.00 2.1±0.01ns ? ?/sec 3.08 6.5±0.05ns ? ?/sec
681 date/add_days/sameyear/span 1.00 6.5±0.05ns ? ?/sec
682 date/difference_days/duration 1.18 3.4±0.04ns ? ?/sec 1.00 2.9±0.02ns ? ?/sec
683 date/difference_days/span 1.00 2.5±0.02ns ? ?/sec
684 date/tomorrow/diff-month 1.00 0.4±0.00ns ? ?/sec 3.25 1.3±0.01ns ? ?/sec
685 date/tomorrow/diff-year 1.16 1.7±0.01ns ? ?/sec 1.00 1.4±0.01ns ? ?/sec
686 date/tomorrow/same-month 1.00 0.4±0.00ns ? ?/sec 1.99 0.8±0.00ns ? ?/sec
687 date/yesterday/diff-month 1.00 0.4±0.02ns ? ?/sec 3.17 1.3±0.01ns ? ?/sec
688 date/yesterday/diff-year 1.85 2.0±0.01ns ? ?/sec 1.00 1.1±0.01ns ? ?/sec
689 date/yesterday/same-month 1.00 0.4±0.03ns ? ?/sec 1.72 0.7±0.02ns ? ?/sec
690 parse/civil_datetime 2.95 73.6±0.72ns ? ?/sec 1.00 24.9±0.19ns ? ?/sec
691 parse/rfc2822 3.09 59.9±0.30ns ? ?/sec 1.00 19.3±0.17ns ? ?/sec
692 parse/strptime/oneshot 3.11 197.8±0.80ns ? ?/sec 1.00 63.6±1.19ns ? ?/sec
693 parse/strptime/prebuilt 1.00 77.1±1.44ns ? ?/sec
694 print/civil_datetime 13.10 147.4±0.60ns ? ?/sec 1.00 11.3±0.04ns ? ?/sec
695 print/iso8601_duration/long-time/duration/buffer 2.38 46.5±0.34ns ? ?/sec 1.00 19.5±0.04ns ? ?/sec
696 print/iso8601_duration/long-time/duration/to_string 3.13 71.7±0.36ns ? ?/sec 1.00 23.0±0.07ns ? ?/sec
697 print/iso8601_duration/short/duration/buffer 2.65 32.3±0.30ns ? ?/sec 1.00 12.2±0.04ns ? ?/sec
698 print/iso8601_duration/short/duration/to_string 2.08 36.8±0.33ns ? ?/sec 1.00 17.7±0.05ns ? ?/sec
699 print/iso8601_duration/tiny/duration/buffer 2.74 31.6±0.32ns ? ?/sec 1.00 11.6±0.03ns ? ?/sec
700 print/iso8601_duration/tiny/duration/to_string 2.28 36.5±0.40ns ? ?/sec 1.00 16.0±0.08ns ? ?/sec
701 print/rfc2822/buffer 4.91 64.6±0.59ns ? ?/sec 1.00 13.2±0.03ns ? ?/sec
702 print/rfc2822/to_string 5.75 111.0±0.37ns ? ?/sec 1.00 19.3±0.05ns ? ?/sec
703 print/rfc3339/buffer 3.79 64.2±0.56ns ? ?/sec 1.00 17.0±0.14ns ? ?/sec
704 print/rfc3339/to_string 4.75 112.4±0.33ns ? ?/sec 1.00 23.6±0.11ns ? ?/sec
705 print/rfc9557/buffer 1.00 16.2±0.05ns ? ?/sec
706 print/rfc9557/to_string 1.00 22.2±0.07ns ? ?/sec
707 print/strftime/oneshot/buffer 3.90 213.9±1.99ns ? ?/sec 1.00 54.8±0.32ns ? ?/sec
708 print/strftime/oneshot/to_string 3.63 261.3±1.26ns ? ?/sec 1.00 72.1±0.49ns ? ?/sec
709 print/strftime/oneshot/zoned 1.00 65.5±0.64ns ? ?/sec
710 print/strftime/prebuilt/buffer 1.00 85.4±0.52ns ? ?/sec
711 print/strftime/prebuilt/to_string 1.00 147.4±0.76ns ? ?/sec
712 timestamp/add_time_secs/duration 2.42 6.1±0.08ns ? ?/sec 1.00 2.5±0.03ns ? ?/sec
713 timestamp/add_time_secs/span 1.00 3.8±0.06ns ? ?/sec
714 timestamp/add_time_subsec/duration 2.10 6.1±0.04ns ? ?/sec 1.00 2.9±0.02ns ? ?/sec
715 timestamp/add_time_subsec/span 1.00 8.1±0.09ns ? ?/sec
716 timestamp/every_hour_in_week/byhand 16.15 1679.6±6.13ns ? ?/sec 1.00 104.0±0.72ns ? ?/sec
717 timestamp/every_hour_in_week/series 1.00 105.9±0.66ns ? ?/sec
718 timestamp/from_seconds/integer 14.45 4.7±0.03ns ? ?/sec 1.00 0.3±0.00ns ? ?/sec
719 timestamp/to_civil_datetime_offset_conversion 1.65 7.3±0.02ns ? ?/sec 1.00 4.4±0.04ns ? ?/sec
720 timestamp/to_civil_datetime_offset_holistic 1.00 4.4±0.04ns ? ?/sec
721 timestamp/to_civil_datetime_static/America-New-York/bundled 1.00 16.0±0.16ns ? ?/sec
722 timestamp/to_civil_datetime_static/America-New-York/zoneinfo 1.42 18.4±0.11ns ? ?/sec 1.00 13.0±0.11ns ? ?/sec
723 timestamp/to_civil_datetime_static/Asia-Shanghai/bundled 1.00 15.2±0.16ns ? ?/sec
724 timestamp/to_civil_datetime_static/Asia-Shanghai/zoneinfo 3.16 15.7±0.11ns ? ?/sec 1.00 5.0±0.05ns ? ?/sec
725 zoned/fixed_offset_add_time/duration 1.00 6.1±0.06ns ? ?/sec 1.56 9.5±0.05ns ? ?/sec
726 zoned/fixed_offset_add_time/span 1.00 16.6±0.09ns ? ?/sec
727 zoned/fixed_offset_to_civil_datetime 1.23 5.6±0.01ns ? ?/sec 1.00 4.5±0.01ns ? ?/sec
728 zoned/fixed_offset_to_timestamp 3.15 1.2±0.01ns ? ?/sec 1.00 0.4±0.00ns ? ?/sec
729 ```
730
731 Questions about benchmarks are welcome in
732 [Discussions on GitHub](https://github.com/BurntSushi/jiff/discussions).
733
734 ## [`time`](https://docs.rs/time) (v0.3.36)
735
736 `time` is a Rust datetime library that provides a time zone offset aware
737 datetime type.
738
739 For the following comparisons, a `Cargo.toml` with the following dependencies
740 should be able to run any of the programs in this section:
741
742 ```toml
743 anyhow = "1.0.81"
744 jiff = { version = "0.2.0", features = ["serde"] }
745 time = { version = "0.3.36", features = ["local-offset", "macros", "parsing"] }
746 time-tz = "2.0.0"
747 ```
748
749 ### Time zone database integration
750
751 Like `chrono`, the `time` crate does not come with any out of the box
752 functionality for reading your system's copy of the Time Zone Database.
753 However, there is a third party crate, [`time-tz`](https://docs.rs/time-tz)
754 that provides some time zone support in a fashion similar to `chrono-tz`. That
755 is, it requires bundling the time zone data into your binary and does not
756 support reading the system copy of the Time Zone Database when available.
757
758 Note also that `time` does not provide the extension points necessary in its API
759 to make handling time zone aware datetimes ergonomic. Indeed, many operations
760 are not expressible at all.
761
762 The main thing `time` supports is a concept of "local" time. In particular, it
763 is limited to determining your system's default time zone offset, but nothing
764 more. That is, it doesn't support DST safe arithmetic:
765
766 ```rust
767 use anyhow::Context;
768 use time::{ext::NumericalDuration, macros::datetime, Duration};
769
770 fn main() -> anyhow::Result<()> {
771 // We create a fixed datetime for testing purposes,
772 // but it's the same sort of value we would get back
773 // from `OffsetDateTime::now_local()`.
774 let dt1 = datetime!(2024-03-10 01:30:00 -05:00);
775 let dt2 = dt1.checked_add(1.hours())
776 .context("datetime arithmetic failed")?;
777 // The 2 o'clock hour didn't exist on 2024-03-10
778 // in New York.
779 assert_eq!(dt2.to_string(), "2024-03-10 2:30:00.0 -05:00:00");
780
781 Ok(())
782 }
783 ```
784
785 `time`, in its present design, is fundamentally incapable of doing daylight
786 saving time safe arithmetic because its `OffsetDateTime` type doesn't know
787 anything about the time zone rules. Compare this with Jiff, which lets you not
788 only create a datetime with an offset, but with a _time zone_:
789
790 ```rust
791 use jiff::{civil::date, ToSpan};
792
793 fn main() -> anyhow::Result<()> {
794 let zdt1 = date(2024, 3, 10).at(1, 30, 0, 0).in_tz("America/New_York")?;
795 let zdt2 = zdt1.checked_add(1.hour())?;
796 assert_eq!(zdt2.to_string(), "2024-03-10T03:30:00-04:00[America/New_York]");
797
798 Ok(())
799 }
800 ```
801
802 If you use `time-tz`, then you can make the above example with `time` work:
803
804 ```rust
805 use anyhow::Context;
806 use time::{ext::NumericalDuration, macros::datetime, Duration};
807 use time_tz::{OffsetDateTimeExt, Tz};
808
809 fn main() -> anyhow::Result<()> {
810 let tz = time_tz::timezones::db::america::NEW_YORK;
811
812 // We create a fixed datetime for testing purposes,
813 // but it's the same sort of value we would get back
814 // from `OffsetDateTime::now_local()`.
815 let dt1 = datetime!(2024-03-10 01:30:00 -05:00);
816 let dt2 = dt1.checked_add(1.hours())
817 .context("datetime arithmetic failed")?
818 .to_timezone(tz);
819 assert_eq!(dt2.to_string(), "2024-03-10 3:30:00.0 -04:00:00");
820
821 Ok(())
822 }
823 ```
824
825 But note that you have to be careful to call `.to_timezone()` before printing
826 the datetime. In particular, there is no time zone aware datetime type.
827
828 In my comparison with Chrono I went through a lot of examples involving
829 time zones. I did this because Chrono supports DST safe arithmetic generally,
830 but with a lot of nuanced differences from what Jiff supports. Conversely,
831 `time` doesn't have a time zone aware datetime type. And the time zone support
832 provided by `time-tz` is extremely limited. So at this time, in this document,
833 we won't belabor the point.
834
835 ### `time` supports its own custom format description
836
837 Some users may find this easier to use:
838
839 ```rust
840 use time::{macros::format_description, OffsetDateTime};
841
842 fn main() -> anyhow::Result<()> {
843 let format = format_description!(
844 "[year]-[month]-[day] [hour]:[minute]:[second] \
845 [offset_hour sign:mandatory]:[offset_minute]:[offset_second]"
846 );
847 let odt = OffsetDateTime::parse("2024-07-11 22:49:00 -04:00:00", &format)?;
848 assert_eq!(odt.to_string(), "2024-07-11 22:49:00.0 -04:00:00");
849
850 Ok(())
851 }
852 ```
853
854 Jiff does support a `strptime`/`strftime` style API via the
855 `jiff::fmt::strtime` module:
856
857 ```rust
858 use jiff::Zoned;
859
860 fn main() -> anyhow::Result<()> {
861 let zdt = Zoned::strptime(
862 "%Y-%m-%d %H:%M:%S %:z",
863 "2024-07-11 22:49:00 -04:00:00",
864 )?;
865 assert_eq!(zdt.to_string(), "2024-07-11T22:49:00-04:00[-04:00]");
866
867 Ok(())
868 }
869 ```
870
871 `time` also supports `strptime`/`strftime` style APIs:
872
873 ```rust
874 use time::OffsetDateTime;
875
876 fn main() -> anyhow::Result<()> {
877 // I don't believe `time` supports `%:z`, so we just drop the colons here.
878 let format = time::format_description::parse_strftime_borrowed(
879 "%Y-%m-%d %H:%M:%S %z"
880 )?;
881 let odt = OffsetDateTime::parse("2024-07-11 22:49:00 -0400", &format)?;
882 assert_eq!(odt.to_string(), "2024-07-11 22:49:00.0 -04:00:00");
883
884 Ok(())
885 }
886 ```
887
888 ### Jiff supports rounding datetimes
889
890 We use a `Zoned` with a `TimeZone` that has a fixed offset. This is same as
891 `time`'s `OffsetDateTime` type:
892
893 ```rust
894 use jiff::{civil::date, tz::{self, TimeZone}, Unit, Zoned};
895
896 fn main() -> anyhow::Result<()> {
897 let tz = TimeZone::fixed(tz::offset(-4));
898 let zdt1 = date(2024, 7, 11).at(16, 46, 0, 0).to_zoned(tz)?;
899 let zdt2 = zdt1.round(Unit::Hour)?;
900 assert_eq!(zdt2.to_string(), "2024-07-11T17:00:00-04:00[-04:00]");
901
902 Ok(())
903 }
904 ```
905
906 Note though that because Jiff has support for time zones, you generally
907 shouldn't need to (and shouldn't _want_ to) use fixed offset datetimes. It's
908 because they don't take time zone rules into account and thus do not provide
909 DST safe arithmetic. Instead, the code above should be written like this
910 (unless you have a very specific reason to do otherwise):
911
912 ```rust
913 use jiff::{civil::date, Unit};
914
915 fn main() -> anyhow::Result<()> {
916 // Can also use `.to_zoned(TimeZone::system())` to use your system's
917 // default time zone.
918 let zdt1 = date(2024, 7, 11).at(16, 46, 0, 0).in_tz("America/New_York")?;
919 let zdt2 = zdt1.round(Unit::Hour)?;
920 assert_eq!(zdt2.to_string(), "2024-07-11T17:00:00-04:00[America/New_York]");
921
922 Ok(())
923 }
924 ```
925
926 From here on, we won't use fixed offset datetimes in order to avoid encouraging
927 their use.
928
929 The `time` crate has no rounding APIs.
930
931 ### Jiff supports rounding durations
932
933 In Jiff, one can round the duration computed between two datetimes
934
935 ```rust
936 use jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDifference};
937
938 fn main() -> anyhow::Result<()> {
939 let zdt1 = date(2001, 11, 18).at(8, 30, 0, 0).in_tz("America/New_York")?;
940 let zdt2 = date(2024, 7, 11).at(22, 38, 0, 0).in_tz("America/New_York")?;
941
942 let round_options = ZonedDifference::new(&zdt2)
943 .largest(Unit::Year)
944 .smallest(Unit::Day)
945 .mode(RoundMode::HalfExpand);
946 let span = zdt1.until(round_options)?;
947 assert_eq!(span, 22.years().months(7).days(24).fieldwise());
948
949 Ok(())
950 }
951 ```
952
953 The `time` crate has no rounding APIs.
954
955 ### Jiff provides support for calendar arithmetic
956
957 With Jiff, you can add durations with calendar units:
958
959 ```rust
960 use jiff::{civil::date, ToSpan};
961
962 fn main() -> anyhow::Result<()> {
963 let zdt1 = date(2024, 7, 11).at(21, 0, 0, 0).in_tz("America/New_York")?;
964 let zdt2 = zdt1.checked_add(2.years().months(6).days(1))?;
965 assert_eq!(zdt2.to_string(), "2027-01-12T21:00:00-05:00[America/New_York]");
966
967 Ok(())
968 }
969 ```
970
971 The `time` crate does provide a way to construct a `Duration` from units of
972 days via `Duration::days`, but this of course requires assuming that all days
973 are 24 hours long. And `time` does not support adding years or months.
974
975 ### Jiff supports conveniently re-balancing durations
976
977 Aside from calendar arithmetic, Jiff also supports re-balancing durations
978 based on what you want the largest unit to be:
979
980 ```rust
981 use jiff::{SpanRound, ToSpan, Unit};
982
983 fn main() -> anyhow::Result<()> {
984 // Balance down to seconds.
985 let span1 = 4.hours().minutes(36).seconds(59);
986 let span2 = span1.round(SpanRound::new().largest(Unit::Second))?;
987 assert_eq!(span2, 16_619.seconds().fieldwise());
988
989 // Now go back by balancing up to hours.
990 let span1 = 16_619.seconds();
991 let span2 = span1.round(SpanRound::new().largest(Unit::Hour))?;
992 assert_eq!(span2, 4.hours().minutes(36).seconds(59).fieldwise());
993
994 Ok(())
995 }
996 ```
997
998 The `time` crate's `Duration` type can go from bigger units down to smaller
999 units easily enough:
1000
1001 ```rust
1002 use time::{ext::NumericalDuration, Duration};
1003
1004 fn main() -> anyhow::Result<()> {
1005 let span = 4.hours() + 36.minutes() + 59.seconds();
1006 assert_eq!(span.whole_seconds(), 16_619);
1007 Ok(())
1008 }
1009 ```
1010
1011 But going from smaller units back up to larger units is difficult:
1012
1013 ```rust
1014 use time::{ext::NumericalDuration, Duration};
1015
1016 fn main() -> anyhow::Result<()> {
1017 let span = 16_619.seconds();
1018 assert_eq!(span.whole_hours(), 4);
1019 assert_eq!(span.whole_minutes(), 276);
1020 assert_eq!(span.whole_seconds(), 16_619);
1021
1022 Ok(())
1023 }
1024 ```
1025
1026 Notice that the accessors just report how many whole units the span is. You
1027 can't get the span broken down into smaller units. To achieve that, you need to
1028 do the arithmetic yourself:
1029
1030 ```rust
1031 use time::{convert::{Hour, Minute, Second}, ext::NumericalDuration, Duration};
1032
1033 fn main() -> anyhow::Result<()> {
1034 let mut span = 16_619.seconds();
1035 assert_eq!(span.whole_hours(), 4);
1036 assert_eq!(span.whole_minutes() % Minute::per(Hour) as i64, 36);
1037 assert_eq!(span.whole_seconds() % Second::per(Minute) as i64, 59);
1038
1039 Ok(())
1040 }
1041 ```
1042
1043 ### Jiff is generally faster than `time`
1044
1045 When it comes to parsing and printing, Jiff is generally faster than `time`
1046 although not always. `time` is sometimes faster than Jiff on date arithmetic,
1047 but not by much. (Some of these may be due to faster equality comparisons on
1048 date values, on which `time` is legitimately faster at than Jiff at present.)
1049
1050 The following results were collected with `time 0.3.47`.
1051
1052 ```text
1053 $ cd bench
1054 $ cargo bench -- --save-baseline baseline
1055 [.. snip ..]
1056 $ critcmp base -g '(.*)/(?:jiff|time)$'
1057 group baseline//time baseline//jiff
1058 ----- -------------- --------------
1059 civil_datetime/add_days/diffyear/duration 1.00 7.8±0.08ns ? ?/sec 1.67 12.9±0.19ns ? ?/sec
1060 civil_datetime/add_days/diffyear/span 1.00 18.0±0.28ns ? ?/sec
1061 civil_datetime/add_days/sameyear/duration 1.00 7.8±0.11ns ? ?/sec 1.66 12.9±0.16ns ? ?/sec
1062 civil_datetime/add_days/sameyear/span 1.00 18.0±0.25ns ? ?/sec
1063 date/add_days/diffyear/duration 1.00 3.8±0.02ns ? ?/sec 1.67 6.3±0.04ns ? ?/sec
1064 date/add_days/diffyear/span 1.00 4.9±0.05ns ? ?/sec
1065 date/add_days/one/duration 1.00 3.8±0.03ns ? ?/sec 1.38 5.2±0.03ns ? ?/sec
1066 date/add_days/one/span 1.00 5.8±0.06ns ? ?/sec
1067 date/add_days/sameyear/duration 1.00 3.8±0.04ns ? ?/sec 1.68 6.4±0.07ns ? ?/sec
1068 date/add_days/sameyear/span 1.00 4.9±0.05ns ? ?/sec
1069 date/days_in_month/leap/feb 1.90 1.1±0.01ns ? ?/sec 1.00 0.6±0.03ns ? ?/sec
1070 date/days_in_month/leap/nofeb 2.70 1.0±0.01ns ? ?/sec 1.00 0.4±0.00ns ? ?/sec
1071 date/days_in_month/noleap/feb 2.78 1.1±0.02ns ? ?/sec 1.00 0.4±0.01ns ? ?/sec
1072 date/days_in_month/noleap/nofeb 2.70 1.0±0.02ns ? ?/sec 1.00 0.4±0.00ns ? ?/sec
1073 date/difference_days/duration 1.00 2.1±0.02ns ? ?/sec 1.41 2.9±0.04ns ? ?/sec
1074 date/difference_days/span 1.00 2.4±0.03ns ? ?/sec
1075 date/tomorrow/diff-month 1.00 0.4±0.02ns ? ?/sec 3.42 1.4±0.01ns ? ?/sec
1076 date/tomorrow/diff-year 1.00 1.0±0.01ns ? ?/sec 1.59 1.5±0.01ns ? ?/sec
1077 date/tomorrow/same-month 1.00 0.4±0.00ns ? ?/sec 2.25 0.9±0.01ns ? ?/sec
1078 date/yesterday/diff-month 1.00 0.4±0.01ns ? ?/sec 3.65 1.4±0.02ns ? ?/sec
1079 date/yesterday/diff-year 1.00 0.9±0.01ns ? ?/sec 1.35 1.2±0.02ns ? ?/sec
1080 date/yesterday/same-month 1.00 0.4±0.02ns ? ?/sec 2.06 0.8±0.01ns ? ?/sec
1081 datetime/add_years_months_days 1.00 29.1±0.18ns ? ?/sec
1082 parse/civil_datetime 1.00 12.9±0.19ns ? ?/sec 1.63 21.1±0.19ns ? ?/sec
1083 parse/rfc2822 2.24 43.4±1.90ns ? ?/sec 1.00 19.4±0.15ns ? ?/sec
1084 parse/strptime/oneshot 1.00 62.2±0.39ns ? ?/sec
1085 parse/strptime/prebuilt 1.00 73.7±0.91ns ? ?/sec
1086 print/civil_datetime 3.27 37.4±0.32ns ? ?/sec 1.00 11.4±0.04ns ? ?/sec
1087 print/rfc2822/buffer 1.55 20.4±0.08ns ? ?/sec 1.00 13.2±0.05ns ? ?/sec
1088 print/rfc2822/to_string 3.61 72.0±1.25ns ? ?/sec 1.00 19.9±0.06ns ? ?/sec
1089 print/rfc3339/buffer 1.33 22.1±0.29ns ? ?/sec 1.00 16.7±0.11ns ? ?/sec
1090 print/rfc3339/to_string 2.91 68.1±1.30ns ? ?/sec 1.00 23.4±0.12ns ? ?/sec
1091 print/rfc9557/buffer 1.00 16.2±0.07ns ? ?/sec
1092 print/rfc9557/to_string 1.00 22.6±0.20ns ? ?/sec
1093 print/strftime/oneshot/buffer 6.88 421.5±1.39ns ? ?/sec 1.00 61.3±0.82ns ? ?/sec
1094 print/strftime/oneshot/to_string 5.59 434.0±1.44ns ? ?/sec 1.00 77.7±0.96ns ? ?/sec
1095 print/strftime/oneshot/zoned 1.00 74.6±1.07ns ? ?/sec
1096 print/strftime/prebuilt/buffer 1.00 97.7±0.99ns ? ?/sec
1097 print/strftime/prebuilt/buffer/bespoke 1.00 105.8±1.45ns ? ?/sec
1098 print/strftime/prebuilt/to_string 1.00 165.3±1.19ns ? ?/sec
1099 print/strftime/prebuilt/to_string/bespoke 1.00 175.0±1.79ns ? ?/sec
1100 timestamp/add_time_secs/duration 3.82 9.6±0.04ns ? ?/sec 1.00 2.5±0.03ns ? ?/sec
1101 timestamp/add_time_secs/span 1.00 3.7±0.05ns ? ?/sec
1102 timestamp/add_time_subsec/duration 3.33 9.7±0.09ns ? ?/sec 1.00 2.9±0.03ns ? ?/sec
1103 timestamp/add_time_subsec/span 1.00 7.8±0.08ns ? ?/sec
1104 timestamp/every_hour_in_week/byhand 14.30 1530.8±16.96ns ? ?/sec 1.00 107.1±0.74ns ? ?/sec
1105 timestamp/every_hour_in_week/series 1.00 105.8±1.01ns ? ?/sec
1106 timestamp/from_seconds/integer 11.69 4.4±0.03ns ? ?/sec 1.00 0.4±0.01ns ? ?/sec
1107 timestamp/to_civil_datetime_offset_conversion 1.00 3.9±0.03ns ? ?/sec 1.49 5.8±0.04ns ? ?/sec
1108 timestamp/to_civil_datetime_offset_holistic 1.00 4.6±0.03ns ? ?/sec 1.04 4.8±0.04ns ? ?/sec
1109 zoned/fixed_offset_add_time/duration 1.00 9.6±0.09ns ? ?/sec 1.06 10.3±0.08ns ? ?/sec
1110 zoned/fixed_offset_add_time/span 1.00 16.9±0.12ns ? ?/sec
1111 zoned/fixed_offset_to_civil_datetime 1.00 0.6±0.00ns ? ?/sec 7.32 4.2±0.01ns ? ?/sec
1112 zoned/fixed_offset_to_timestamp 6.08 1.8±0.02ns ? ?/sec 1.00 0.3±0.01ns ? ?/sec
1113 ```
1114
1115 Questions about benchmarks are welcome in
1116 [Discussions on GitHub](https://github.com/BurntSushi/jiff/discussions).
1117
1118 ## [`hifitime`](https://docs.rs/hifitime) (v3.9.0)
1119
1120 `hifitime` is a datetime library with a focus on engineering and scientific
1121 calculations where general relativity and time dilation matter. It supports
1122 conversion between many different time scales: TAI, Terrestrial Time, UTC, GPST
1123 and more. It also supports leap seconds.
1124
1125 For the following comparisons, a `Cargo.toml` with the following dependencies
1126 should be able to run any of the programs in this section:
1127
1128 ```toml
1129 anyhow = "1.0.81"
1130 hifitime = "3.9.0"
1131 jiff = { version = "0.2.0", features = ["serde"] }
1132 ```
1133
1134 ### Time zone database integration
1135
1136 Like the `time` crate, `hifitime` does not support time zones and does not have
1137 any integration with the Time Zone Database. `hifitime` doesn't have any
1138 equivalent to `OffsetDateTime` like in `time` either. The only datetime type
1139 that `hifitime` has is `Epoch`, and it is an absolute time. While you can
1140 convert between it and civil time (assuming civil time is in UTC), there is no
1141 data type in `hifitime` for representing civil time.
1142
1143 ### `hifitime` supports leap seconds
1144
1145 In particular, when computing a duration from two `Epoch` values that spans
1146 a positive leap second (a second gets repeated), `hifitime` will correctly
1147 report the accurate duration. With that said, to get an accurate duration, one
1148 of the two time scales has to be converted to to TAI (or another time scale
1149 which does not have leap seconds):
1150
1151 ```rust
1152 use hifitime::{Duration, Epoch, TimeScale};
1153
1154 fn main() -> anyhow::Result<()> {
1155 let e1: Epoch = "2015-06-30T23:00:00 UTC".parse()?;
1156 let e2: Epoch = "2015-07-01T00:00:00 UTC".parse()?;
1157 let e2 = e2.to_time_scale(TimeScale::TAI);
1158
1159 let duration = e2 - e1;
1160 assert_eq!(duration, Duration::from_seconds(3_601.0));
1161
1162 Ok(())
1163 }
1164 ```
1165
1166 Jiff, however, [does not support leap seconds][jiff-leap-seconds]:
1167
1168 ```rust
1169 use jiff::{Timestamp, ToSpan};
1170
1171 fn main() -> anyhow::Result<()> {
1172 let ts1: Timestamp = "2015-06-30T23:00:00Z".parse()?;
1173 let ts2: Timestamp = "2015-07-01T00:00:00Z".parse()?;
1174 let span = ts2 - ts1;
1175 assert_eq!(span, 3_600.seconds().fieldwise());
1176
1177 Ok(())
1178 }
1179 ```
1180
1181 So in this case, Jiff reports `3,600` seconds as the duration, but the _actual_
1182 duration was `3,601` seconds, as reported by `hifitime`.
1183
1184 [jiff-leap-seconds]: https://github.com/BurntSushi/jiff/issues/7
1185
1186 ### Jiff makes checked or saturating arithmetic explicit
1187
1188 For Jiff, whether you want to saturate or not is an explicit part of the API.
1189 And implementations of the `Add` operator will panic on overflow:
1190
1191 ```rust
1192 use jiff::{Timestamp, ToSpan};
1193
1194 fn main() -> anyhow::Result<()> {
1195 let ts = Timestamp::MAX;
1196 assert!(ts.checked_add(1.day()).is_err());
1197 assert_eq!(ts.saturating_add(1.hour())?, ts);
1198
1199 Ok(())
1200 }
1201 ```
1202
1203 In contrast, `hifitime` appears to use saturating arithmetic everywhere (I've
1204 not been able to find this behavior documented though, so I'm not clear on what
1205 the intended semantics are):
1206
1207 ```rust
1208 use hifitime::{Duration, Epoch};
1209
1210 fn main() -> anyhow::Result<()> {
1211 let e1 = Epoch::from_unix_seconds(f64::MAX);
1212 let e2 = e1 + Duration::from_days(1.0);
1213 assert_eq!(e1, e2);
1214
1215 Ok(())
1216 }
1217 ```
1218
1219
1220 ## [`icu`](https://docs.rs/icu) (v1.5.0)
1221
1222 The ICU4X project fulfils a slightly different need than `jiff`. Its main
1223 features are calendrical calculations (`icu::calendar`), supporting conversions
1224 between different calendar systems such as Gregorian, Buddhist, Islamic,
1225 Japanese, etc., as well as localized datetime formatting (`icu::datetime`).
1226
1227 It does not perform datetime or time-zone arithmetic, and does not have a
1228 timestamp or duration type.
1229
1230 `icu` can be used to complement `jiff` when localized date formatting or
1231 calendar conversions are required. To facilitate this, the
1232 [`jiff-icu`](https://docs.rs/jiff-icu) crate makes conversions between Jiff
1233 and ICU4X data types seamless. For example, to do localization starting from
1234 a Jiff data type:
1235
1236 ```text
1237 use icu::{
1238 calendar::{japanese::Japanese, DateTime},
1239 datetime::TypedDateTimeFormatter,
1240 locid::locale,
1241 };
1242 use jiff::Timestamp;
1243 use jiff_icu::ConvertFrom as _;
1244
1245 fn main() -> anyhow::Result<()> {
1246 let ts: Timestamp = "2024-09-10T23:37:20Z".parse()?;
1247 let zoned = ts.in_tz("Asia/Tokyo")?;
1248
1249 // Create ICU datetime.
1250 let datetime = DateTime::convert_from(zoned.datetime());
1251
1252 // Convert to Japanese calendar.
1253 let japanese_datetime = DateTime::new_from_iso(datetime, Japanese::new());
1254
1255 // Format for the en-GB locale.
1256 let formatter = TypedDateTimeFormatter::try_new(
1257 &locale!("en-GB").into(),
1258 Default::default(),
1259 )?;
1260
1261 // Assert that we get the expected result.
1262 assert_eq!(
1263 formatter.format(&japanese_datetime).to_string(),
1264 "Sept 11, 6 Reiwa, 08:37:20",
1265 );
1266
1267 Ok(())
1268 }
1269 ```
1270
1271 The above example requires the following dependency specifications:
1272
1273 ```toml
1274 anyhow = "1.0.81"
1275 icu = { version = "1.5.0", features = ["std"] }
1276 jiff = { version = "0.1.0", features = ["serde"] }
1277 jiff-icu = { version = "0.1.0" }
1278 ```