| 1 | # The API design rationale for Jiff |
| 2 | |
| 3 | This document discusses some of the design decisions that led to Jiff's API. |
| 4 | The purpose of writing this document is to help folks understand _why_ Jiff's |
| 5 | API is the way it is, above and beyond "Jiff did it this way to match |
| 6 | [Temporal]." |
| 7 | |
| 8 | This document is written as an FAQ, although it is restricted in scope to the |
| 9 | API design of Jiff. This isn't a FAQ for questions like, "How do I add 1 day |
| 10 | to a zoned datetime?" |
| 11 | |
| 12 | Unlike "[Comparison with other Rust datetime crates][comparison]," this |
| 13 | document is _opinionated_. That is, some value judgments are expressed that are |
| 14 | opinion based, and on which reasonable people may disagree. |
| 15 | |
| 16 | |
| 17 | ## Why name the library "jiff"? |
| 18 | |
| 19 | I wanted something short and related to time for the library name. Most of the |
| 20 | "obvious" names are taken. |
| 21 | |
| 22 | I thought a lot about phrases or words that had some connection to time. There |
| 23 | are more than you think. One phrase I heard a lot as a kid who grew up in New |
| 24 | England was, "I'll be back in a jiff" or "I'll be back in a jiffy." The meaning |
| 25 | of that phrase was, roughly, "I'll be back very soon." So "jiff" refers to some |
| 26 | "short span of time." Since "jiff" was shorter than "jiffy," that's what I went |
| 27 | with. |
| 28 | |
| 29 | Jiff is pronounced like "gif" with a soft "g," as in "gem." |
| 30 | |
| 31 | |
| 32 | ## Why build another datetime library? |
| 33 | |
| 34 | At the time of writing, there are four existing prominent datetime libraries |
| 35 | for Rust: [`chrono`], [`time`], [`hifitime`] and [`icu`]. "[Comparison with |
| 36 | other Rust datetime crates][comparison]" goes over the "facts of comparison" |
| 37 | between the crates (mostly for just `chrono` and `time`), but it intentionally |
| 38 | leaves out value judgments. To answer this question, I have to introduce value |
| 39 | judgments and my opinions on existing libraries. **These are opinions on which |
| 40 | reasonable people can disagree.** Moreover, since these are opinions meant to |
| 41 | justify an alternative, these opinions tend to be oriented on the faults (as |
| 42 | this author sees them) in existing crates as opposed to their benefits. |
| 43 | |
| 44 | Broadly speaking, my view on Rust datetime libraries was that they had reached |
| 45 | a local maximum, and there didn't seem to be much movement toward breaking out |
| 46 | of that local maximum and getting to something that was categorically better. |
| 47 | Much of my thoughts revolve around not just the functionality provided, but |
| 48 | also the API design of these crates. Thus, I perceived a gap in the ecosystem |
| 49 | that I felt like I could fill. |
| 50 | |
| 51 | I'll share my brief thoughts on each crate. I'll cover "why not contribute to |
| 52 | an existing library and make it better" in the next question. |
| 53 | |
| 54 | ### `chrono` |
| 55 | |
| 56 | In my view, Chrono is the closest to Jiff in terms of the functionality it |
| 57 | provides. It has some support for DST safe arithmetic for example, and even |
| 58 | some support for doing calendar math. But its support is incomplete. While one |
| 59 | can add units of days to Chrono datetimes, Chrono lacks the ability to do math |
| 60 | on multiple calendar units at the same time. Moreover, Chrono cannot _produce_ |
| 61 | calendar durations between two time zone aware datetimes. |
| 62 | |
| 63 | Moreover, Chrono's integration with the [IANA Time Zone Database] is somewhat |
| 64 | spotty. Support for it isn't included in the `chrono` crate itself, but |
| 65 | is instead something you need to opt into with additional crates, such |
| 66 | as [`chrono-tz`] or [`tzfile`]. And each crate comes with its own set of |
| 67 | trade-offs. `chrono-tz` embeds the entire database into your binary and makes |
| 68 | the time zones available at compile time, while `tzfile` reads the database |
| 69 | from your system's copy of the database (i.e., `/usr/share/zoneinfo` on Unix). |
| 70 | In my view, this creates a difficult situation for non-expert users of Chrono |
| 71 | where the "right" choice isn't obvious. In my opinion, the _default_ should be |
| 72 | to read time zone transition data from the system's copy of the database on |
| 73 | disk, and only bundle the data into the binary as a last resort when a copy of |
| 74 | the database isn't reliably available (like on Windows). The main reason for |
| 75 | this is that the database is frequently updated (a few times each year) since |
| 76 | the rules for time zone transitions can change. If that time zone data is |
| 77 | embedded into your binary, then you need to 1) wait for `chrono-tz` to update |
| 78 | their data and 2) re-compile your application and ship it out to users. |
| 79 | |
| 80 | In contrast, Jiff _abstracts_ the method of time zone data discovery. That |
| 81 | is, there are no API differences between "read time zone data from the system |
| 82 | database" and "read embedded time zone data." Of course, Jiff provides options |
| 83 | to choose which method to use (like forcing bundling on Unix), but all of this |
| 84 | is transparent to users of Jiff itself. That is, _Jiff tries to do the right |
| 85 | thing by default_. There's no need to go off and find a different crate to |
| 86 | handle time zone data for you. |
| 87 | |
| 88 | While on the topic of time zones, Chrono also has no support for serializing |
| 89 | IANA time zone identifiers. This implies that if you have a time zone aware |
| 90 | datetime in Chrono (whether by `chrono-tz` or `tzfile`), then you can't |
| 91 | losslessly serialize and deserialize it. Namely, serialization will lose |
| 92 | the time zone the datetime is associated with, and instead only include |
| 93 | the offset. Then when it's deserialized, you're left with an offset-only |
| 94 | datetime that won't, for example, provide DST safe arithmetic based on the |
| 95 | original time zone. In contrast, Jiff follows [RFC 9557] to support embedding |
| 96 | IANA time zone identifiers in the serialized representation. For example, |
| 97 | `2024-07-21T17:11-04[America/New_York]`. |
| 98 | |
| 99 | There are a variety of other things that Jiff supports which Chrono does |
| 100 | not, but that's covered in [the comparison section between Jiff and |
| 101 | Chrono][comparison-chrono]. |
| 102 | |
| 103 | As for API design, I found Chrono's API to be overengineered and difficult to |
| 104 | deal with. This is a frustratingly vague complaint, but here are some things |
| 105 | that I believe contribute to that opinion: |
| 106 | |
| 107 | * I've used Chrono for various things, and I found it very difficult to figure |
| 108 | out from its API what the right operations to use were. |
| 109 | * Chrono has been steadily deprecating huge portions of its API in favor of |
| 110 | fallible routines. I find the resulting documentation difficult to read and the |
| 111 | naming to be very clunky. |
| 112 | * The fallible routines return a mixture of `Option<T>` and `Result<T, E>`. |
| 113 | This is frustrating in my experience because the `Option<T>` _usually_ needs to |
| 114 | be converted to a human readable error message, and I think the library should |
| 115 | make use of its contextual information to do this for you. Indeed, Jiff rarely |
| 116 | returns `Option<T>` and instead returns `Result<T, E>` with a contextualized |
| 117 | human readable error message. (Although I'm sure the error messages could use a |
| 118 | lot of improvement.) |
| 119 | * I find the use of generics in Chrono to be overengineered. It has some |
| 120 | key benefits, for example, making the notion of "time zone" an open concept |
| 121 | that can be defined by users of the crate. But in my opinion, this is rarely |
| 122 | needed. The Chrono crate ecosystem makes use of this via the `chrono-tz` and |
| 123 | `tzfile` crates, but Jiff covers both of those use cases (broadly speaking) |
| 124 | automatically. |
| 125 | * Chrono overall puts a large emphasis on "fixed offset" datetimes, but these |
| 126 | are rarely the right abstraction to use. It's possible this is due to the fact |
| 127 | that IANA time zone support is external to Chrono itself. Instead, Jiff just |
| 128 | tries to do the right thing by default, and gives users IANA time zone support |
| 129 | out of the box. Jiff does support fixed offset datetimes as well, but they are |
| 130 | de-emphasized. |
| 131 | * I find generic traits like `Datelike` to also be very confusing because they |
| 132 | split the APIs of types like `NaiveDate` into concrete methods and generic |
| 133 | methods, and there's no obvious rhyme or reason as to how those methods are |
| 134 | split up. |
| 135 | * Chrono's API doesn't offer clean on-ramps from civil ("naive") datetimes to |
| 136 | time zone aware datetimes. For example, Chrono provides `NaiveDate::succ_opt` |
| 137 | to get the next day, but this method isn't available on `NaiveDateTime` or |
| 138 | `DateTime`. Instead, to implement it correctly on `DateTime`, you have to get |
| 139 | the naive date, get the date for tomorrow via `succ_opt`, and then convert |
| 140 | it back to the same `NaiveDateTime` and finally make it time zone aware by |
| 141 | applying the original time zone to it. In contrast, in Jiff, it's just a matter |
| 142 | of calling `Zoned::tomorrow`. Indeed, (almost) any method you can call on |
| 143 | `civil::Date` in Jiff is also available on `civil::DateTime` and likewise for |
| 144 | `Zoned`. This makes transitioning between datetime types very easy. Chrono |
| 145 | almost appears to provide this same experience via traits like `Datelike`, |
| 146 | but doesn't fully commit and, in my opinion, the end result has a feeling of |
| 147 | arbitrariness to it. |
| 148 | * Chrono lacks a standard timestamp type. You can approximate this with a |
| 149 | `DateTime<Utc>`, but it's a more complicated type that includes a full datetime |
| 150 | representation. In contrast, Jiff provides a `Timestamp` type for when you just |
| 151 | want the number of seconds from the Unix epoch. And then integrates it with the |
| 152 | rest of the datetime types in a consistent way. |
| 153 | |
| 154 | ### `time` |
| 155 | |
| 156 | My main gripe with the `time` crate is that it has no [IANA Time Zone Database] |
| 157 | support at all. This means it cannot do DST safe arithmetic. Consequently, it |
| 158 | emphasizes the use of "fixed offset" datetimes in a similar fashion as Chrono, |
| 159 | except `time` does not provide any extension mechanism like a `TimeZone` trait. |
| 160 | In my view, fixed offset datetimes are rarely the right thing to use. In my |
| 161 | opinion, this makes writing correct datetime code with the `time` crate rather |
| 162 | difficult. In contrast, Jiff provides full [IANA Time Zone Database] support, |
| 163 | and it should be very rare to need fixed offset datetimes (although Jiff does |
| 164 | support them via `TimeZone::fixed`). |
| 165 | |
| 166 | The `time` crate also, at present, relies on unsound `libc` APIs for |
| 167 | determining the current time zone offset, but makes them sound by requiring (by |
| 168 | default) that `UtcOffset::current_local_offset` is only called when there is |
| 169 | only 1 thread. This is a result of the `libc` APIs accessing the environment |
| 170 | in a way that is unsynchronized with Rust's standard library access to the |
| 171 | environment. This is likely a temporary limitation, but at time of writing, |
| 172 | this state has persisted for quite some time already. In contrast, Jiff detects |
| 173 | the current time zone of the platform on its own without use of `libc`, and |
| 174 | thus sidesteps this issue. (This is also what Chrono does.) |
| 175 | |
| 176 | I overall find the API of `time` to be easier to understand than Chrono, likely |
| 177 | because there are fewer generics. But `time` is also supporting a lot less than |
| 178 | Chrono and Jiff (because of the missing time zone support). |
| 179 | |
| 180 | As with Chrono, I've done a |
| 181 | [more detailed comparison between Jiff and `time`][comparison-time]. |
| 182 | |
| 183 | ### `hifitime` |
| 184 | |
| 185 | `hifitime` is more of a specialized datetime library suited to scientific |
| 186 | applications, and so while Jiff and `hifitime` have overlapping use cases, |
| 187 | `hifitime` fundamentally has a different target demographic than Jiff. As noted |
| 188 | in a [comparison between Jiff and `hifitime`][comparison-hifitime], `hifitime` |
| 189 | doesn't have any time zone support, but it does support conversions between |
| 190 | many different time scales and leap second support. Leap second support, in |
| 191 | this context, means that the durations between two points in time take leap |
| 192 | seconds into account in `hifitime`, but Jiff pretends as if they don't exist. |
| 193 | |
| 194 | In terms of building a new datetime library, I felt like `hifitime` wasn't |
| 195 | really targeting the "general purpose datetime library" use case that I felt |
| 196 | `chrono` and `time` were. And so, whether it existed or not didn't really |
| 197 | impact whether another _general purpose_ datetime library should be built. |
| 198 | |
| 199 | ### `icu` |
| 200 | |
| 201 | `icu` is, as I understand it, still under construction with respect to datetime |
| 202 | support. For example, it doesn't have [IANA Time Zone Database] support. |
| 203 | But, it does support locale aware formatting of datetimes and non-Gregorian |
| 204 | calendars. |
| 205 | |
| 206 | When I started working on Jiff, I didn't have a good understanding of what the |
| 207 | `icu` crate offers. I still don't really. In part because the API is difficult |
| 208 | for me to understand and in part because I haven't dedicated a ton of time to |
| 209 | studying its API. But either way, I don't think it is currently in a position |
| 210 | to be a general purpose datetime library and I wasn't clear on what its goals |
| 211 | were. |
| 212 | |
| 213 | Since I haven't spent a lot of time with `icu`, I didn't have much to say about |
| 214 | it in my [comparison with it and Jiff][comparison-icu]. |
| 215 | |
| 216 | |
| 217 | ## Why not contribute to an existing library instead of building a new one? |
| 218 | |
| 219 | Given that Rust already has at least two prominent datetime libraries, doesn't |
| 220 | adding another one just make things worse? And why not contribute to an |
| 221 | existing library to make it better instead of starting over from scratch? |
| 222 | |
| 223 | I first want to say that I acknowledge that throwing a new crate into the |
| 224 | ecosystem, and adding yet another choice, does actually come with downsides. |
| 225 | There is a cost to having too many choices, and when possible, I do believe it |
| 226 | is better to improve an existing project rather than start a new one. |
| 227 | |
| 228 | Improving existing projects can be difficult. Jiff has a different design than |
| 229 | both `chrono` and `time`. Evolving either one of those crates into what Jiff is |
| 230 | would, in my view, require a huge amount of resources. Not just in time, but in |
| 231 | social capital as well. Because it wouldn't be greenfield development done by |
| 232 | one person making all of the design choices, but instead someone from outside |
| 233 | the project trying to convince the maintainers of established projects to move |
| 234 | in a radically different direction. I know what it's like to be on the side of |
| 235 | maintaining an established API for a library with a lot of users. There is a |
| 236 | huge inertial cost to making sweeping API changes. |
| 237 | |
| 238 | Moreover, when I started Jiff, I was not a domain expert in datetime libraries |
| 239 | or datetime handling in general. Therefore, my opinion that `chrono` and `time` |
| 240 | _could_ be better would arguably not carry a lot of weight. It was only through |
| 241 | the process of actually building a datetime library did I learn enough to form |
| 242 | nuanced opinions about the status quo. When I started, my opinions were much |
| 243 | more vague (but still strong enough to start this project). |
| 244 | |
| 245 | On top of all of this, I was _intrinsically_ motivated to work on this problem. |
| 246 | I found it very interesting, and especially because I perceived there to be a |
| 247 | gap in the ecosystem that I thought I could fill in. I had a vision for what |
| 248 | a datetime library _should_ look like. And it took a lot of iteration to get |
| 249 | from my initial vision to something that works in practice. Doing this on an |
| 250 | existing datetime library with real users would be extremely difficult. |
| 251 | |
| 252 | And speaking as someone who has had folks publish _better_ versions of some of |
| 253 | my own crates, I know what it's like to be on the other end of this. Sometimes |
| 254 | you just have to start fresh. |
| 255 | |
| 256 | |
| 257 | ## Are there any published alternative perspectives on Rust datetime libraries? |
| 258 | |
| 259 | Here's a list. More may be added in the future: |
| 260 | |
| 261 | * [Commentary from the original author of the `chrono` crate.][alt1] |
| 262 | |
| 263 | [alt1]: https://github.com/BurntSushi/jiff/issues/63 |
| 264 | |
| 265 | |
| 266 | ## Why are there two duration types? |
| 267 | |
| 268 | The two duration types provided by Jiff are `Span` and `SignedDuration`. A |
| 269 | `SignedDuration` is effectively identical to a `std::time::Duration`, but it's |
| 270 | signed instead of unsigned. A `Span` is also a duration type, but is likely |
| 271 | different than most other duration types you've used before. |
| 272 | |
| 273 | While a `SignedDuration` can be thought of as a single integer corresponding |
| 274 | to the number of nanoseconds between two points in time, a `Span` is a |
| 275 | collection of individual unit values that combine to represent the difference |
| 276 | between two point in time. Stated more concretely, while the spans `2 |
| 277 | hours` and `120 minutes` both correspond to the same duration of time, when |
| 278 | represented as a Jiff `Span`, they correspond to two distinct values in |
| 279 | memory. This is something that is fundamentally not expressible by a type |
| 280 | like `SignedDuration`, where `2 hours` and `120 minutes` are completely |
| 281 | indistinguishable. |
| 282 | |
| 283 | One of the key advantages of a `Span` is that it can represent units of |
| 284 | non-uniform length. For example, not every month has the same number of days, |
| 285 | but a `Span` can still represent units of months because it tracks the values |
| 286 | of each unit independently. For example, Jiff is smart enough to know that the |
| 287 | difference between `2024-03-01` and `2024-04-01` is the same number of months |
| 288 | as `2024-04-01` and `2024-05-01`, even though the number of days is different: |
| 289 | |
| 290 | ```rust |
| 291 | use jiff::{civil::date, ToSpan, Unit}; |
| 292 | |
| 293 | fn main() -> anyhow::Result<()> { |
| 294 | let date1 = date(2024, 3, 1); |
| 295 | let date2 = date(2024, 4, 1); |
| 296 | let date3 = date(2024, 5, 1); |
| 297 | |
| 298 | // When computing durations between `Date` values, |
| 299 | // the spans default to days. |
| 300 | assert_eq!(date1.until(date2)?, 31.days().fieldwise()); |
| 301 | assert_eq!(date2.until(date3)?, 30.days().fieldwise()); |
| 302 | |
| 303 | // But we can request bigger units! |
| 304 | assert_eq!(date1.until((Unit::Month, date2))?, 1.month().fieldwise()); |
| 305 | assert_eq!(date2.until((Unit::Month, date3))?, 1.month().fieldwise()); |
| 306 | |
| 307 | Ok(()) |
| 308 | } |
| 309 | ``` |
| 310 | |
| 311 | While most folks are very in tune with the fact that years and months have |
| 312 | non-uniform length, a less obvious truth is that days themselves also have |
| 313 | non-uniform length in the presence of time zones. For example, `2024-03-10` in |
| 314 | `America/New_York` was only 23 hours long (the region entered daylight saving |
| 315 | time, creating a gap in time), while `2024-11-03` was 25 hours long (the region |
| 316 | left daylight saving time, creating a fold in time). Being unaware of this |
| 317 | corner case leads to folks assuming that "1 day" and "24 hours" are _always_ |
| 318 | exactly equivalent. But they aren't. The design of Jiff leans into this and |
| 319 | ensures that so long as you're using `Span` to encode a concept of days and are |
| 320 | doing arithmetic with it on `Zoned` values, then you can never get it wrong. |
| 321 | Jiff will always take time zones into account when dealing with units of days |
| 322 | or bigger. |
| 323 | |
| 324 | The design of `Span` comes from [Temporal], which [uses only one duration |
| 325 | type][temporal-one-duration]. From that issue, there are some significant |
| 326 | advantages to using a `Span`. In my own words: |
| 327 | |
| 328 | * It more closely lines up with ISO 8601 durations, which themselves combine |
| 329 | calendar and clock units. |
| 330 | * With a `Span`, it is very easy to move between `5 years 2 months` and |
| 331 | the number of hours in that same span. |
| 332 | * Jiff's `Span` type specifically represents each unit as distinct from the |
| 333 | others. In contrast, most absolute duration types (like `std::time::Duration` |
| 334 | and Jiff's own `SignedDuration`), are "just" a 96-bit integer number of |
| 335 | nanoseconds. This means that, for example, `1 hour 30 minutes` is impossible to |
| 336 | differentiate from `90 minutes`. But depending on the use case, you might want |
| 337 | one or the other. Jiff's `Span` design (copied from Temporal) enables users |
| 338 | to express durations in whatever units they want. And this expression can be |
| 339 | manipulated via APIs like `Span::round` in intuitive ways. |
| 340 | |
| 341 | A `SignedDuration` is still useful in some respects. For example, when you |
| 342 | need tighter integration with the standard library's `std::time::Duration` |
| 343 | (since a `SignedDuration` is the same, but just signed), or when you need |
| 344 | better performance than what `Span` gives you. In particular, since a `Span` |
| 345 | keeps track of the values for each individual unit, it is a much heavier type |
| 346 | than a `SignedDuration`. It uses up more stack space and also required more |
| 347 | computation to do arithmetic with it. |
| 348 | |
| 349 | |
| 350 | ## Why isn't there a `TimeZone` trait? |
| 351 | |
| 352 | First, let's start by explaining what a `TimeZone` is. In Jiff, a `TimeZone` |
| 353 | is a concrete type that cannot be extended by users of Jiff. Instead, users of |
| 354 | Jiff are forced to use one of three different kinds of time zones: |
| 355 | |
| 356 | * A "fixed offset" time zone where the civil time for any particular instant |
| 357 | is computed by simply adding or subtracting a fixed number of seconds from UTC. |
| 358 | The `TimeZone::fixed` constructor enables callers to build time zones with any |
| 359 | offset within the limits imposed by Jiff. |
| 360 | * A [POSIX time zone][POSIX TZ], typically set via the `TZ` environment |
| 361 | variable. These are rarely used by end users, but do provide a way to specify |
| 362 | a rule for when daylight saving time transitions occur thoughtout the year. |
| 363 | (But it does not support historical transitions that might not conform to the |
| 364 | current rule.) The `TimeZone::posix` constructor enables callers to build a |
| 365 | `TimeZone` with a POSIX time zone string. |
| 366 | * [TZif formatted data][RFC 8536], usually from the |
| 367 | [IANA Time Zone Database]. This data contains historical time zone transitions |
| 368 | in addition to rules governing the future in the form of POSIX TZ strings.The |
| 369 | `TimeZone::tzif` constructor enables callers to build a `TimeZone` with any |
| 370 | TZif formatted data. |
| 371 | |
| 372 | The `jiff::tz::TimeZoneDatabase` automatically looks for TZif formatted |
| 373 | files in your system's copy of the IANA Time Zone Database, usually at |
| 374 | `/usr/share/zoneinfo`. (On Windows, Jiff embeds a copy of the IANA Time Zone |
| 375 | Database into the compiled artifact itself.) |
| 376 | |
| 377 | So why isn't `TimeZone` a trait? Well, the above formulation should cover the |
| 378 | _vast majority_ of use cases. And even if that doesn't cover everything, it |
| 379 | is possible for callers to use `TimeZone::tzif` to construct arbitrary time |
| 380 | zones by building their own TZif data. This is a somewhat large hurdle though, |
| 381 | so if this is something that is commonly needed, I'm open to exploring other |
| 382 | options for building custom time zones. For example, perhaps we introduce a way |
| 383 | to describe time zone transitions in Rust code that can then be used to build a |
| 384 | `TimeZone` directly. But, the benefit of TZif is that it is inter-operable and |
| 385 | a standard. There are tools that can build them. |
| 386 | |
| 387 | An important thing to note here is that I actually approach questions like |
| 388 | "Why isn't `TimeZone` a trait?" as instead "Why _should_ `TimeZone` be a trait?" |
| 389 | In particular, I personally perceive costs to introducing generics, especially |
| 390 | on a fundamental type in the crate. For example, if `TimeZone` were a trait, |
| 391 | then `Zoned` would not be a concrete type. It would be generic over a type |
| 392 | parameter that implements the `TimeZone` trait. This in turn implies that |
| 393 | anyone _using_ a `Zoned` in their own types or APIs needs to think about the |
| 394 | `TimeZone` trait and likely incorporate it into their own type signatures. This |
| 395 | is because a `TimeZone` trait implies an open system that infects everything |
| 396 | it touches. The complexity isn't contained. But a concrete `TimeZone` type, |
| 397 | like what Jiff has, encapsulates everything there is about time zones. |
| 398 | |
| 399 | (Making `Zoned` generic over a type parameter with a _default_ type does |
| 400 | contain the complexity in some cases, but not all. I explored using default |
| 401 | type parameters in Jiff for supporting [leap seconds][github-issue-leap], and |
| 402 | it was overall quite awkward in my opinion.) |
| 403 | |
| 404 | The trade off is that we do give up some flexibility. For example, Chrono uses |
| 405 | a `TimeZone` trait design. This enables external crates to provide their own |
| 406 | implementations of the `TimeZone` trait. But the two principle instances of |
| 407 | this occurring, `chrono-tz` and `tzfile`, are both supported by Jiff itself. |
| 408 | With that said, one key advantage of Chrono's design is that it permits its |
| 409 | zone aware datetime type (`DateTime<T>`) to be `Copy` if `T` is `Copy`. It is |
| 410 | somewhat difficult (although not literally impossible) to make a TZif-backed |
| 411 | time zone implement `Copy`, but a _reference_ to it is `Copy` and a reference |
| 412 | to it can still implement Chrono's `TimeZone` trait. (And indeed, this is what |
| 413 | the `tzfile` crate does.) This ultimately leads to more flexibility compared |
| 414 | to Jiff, where its `Zoned` type embeds a `TimeZone` and a `TimeZone` cannot |
| 415 | easily be made `Copy` without giving up something else. |
| 416 | |
| 417 | My opinions on the costs of generics tend to overestimate them compared to many |
| 418 | others in my experience, so your mileage may vary on where you land on this |
| 419 | issue. Buy in my opinion, being able to just write `Zoned` as a concrete type |
| 420 | without any generics is a huge win for comprehensibility. |
| 421 | |
| 422 | |
| 423 | ## Why doesn't `TimeZone` implement `Copy`? |
| 424 | |
| 425 | When initially setting out to build Jiff, I _really_ wanted the `TimeZone` type |
| 426 | to implement `Copy`. The reason why I wanted it to implement `Copy` is because |
| 427 | I wanted all datetime types to have "plain old data" semantics. That is, I want |
| 428 | callers to think of them as small immutable bits of data that can be freely |
| 429 | copied without worry. This makes APIs a little nicer because you can ask for a |
| 430 | `Zoned` instead of a `&Zoned`, assuming the `Zoned` type is small enough. |
| 431 | |
| 432 | But, in order for `Zoned` to be `Copy`, it must be the case that `TimeZone` is |
| 433 | `Copy`. This is because `Zoned` embeds a `TimeZone`. Indeed, this is the reason |
| 434 | for its existence: it couples an instant in time with a particular geographic |
| 435 | region. This makes it possible to expose very ergonomic high level APIs that |
| 436 | don't require the caller to keep passing in a `TimeZone` value repeatedly. |
| 437 | |
| 438 | So, how can a `TimeZone` be `Copy`? Well, both fixed offset and POSIX time |
| 439 | zones could be `Copy`. There's no huge challenge in that. (Internally, a POSIX |
| 440 | time zone is not currently `Copy` because there's no reason for it given what |
| 441 | we're about to discuss.) The main challenge is the TZif-backed time zone. TZif |
| 442 | formatted data can contain an arbitrary number of time zone transitions. There |
| 443 | is just no way to avoid some kind of dynamic memory allocation. |
| 444 | |
| 445 | Since we need dynamic memory allocation, there is really only one way to |
| 446 | make it `Copy` at this point: introduce some kind of caching mechanism with |
| 447 | a small `Copy` identifier that lets us "look up" the time zone in some kind |
| 448 | of global or thread-local cache. I thought a lot about how I might wire this |
| 449 | together, and I could not come up with a satisfactory design. I believe |
| 450 | garbage collection is the main challenge, but also synchronization overhead |
| 451 | for accessing a time zone is likely also a problem. The nice benefit of the |
| 452 | `TimeZone` type as it exists now is that it's just data. While _getting_ a |
| 453 | `TimeZone` from a `TimeZoneDatabase` might require synchronization and possibly |
| 454 | even I/O if the cache for it was invalidated, a `TimeZone` itself requires no |
| 455 | synchronization whatsoever to use it. It is just an `Arc` internally to make it |
| 456 | pointer-sized. |
| 457 | |
| 458 | |
| 459 | ## Why isn't there a `SystemZoned` type? Or a `OffsetZoned` type? |
| 460 | |
| 461 | Some datetime libraries have multiple different zone aware datetime types. Jiff |
| 462 | opts to have just one, and embeds support for the different types of time zones |
| 463 | that most people will ever need into that one type. Jiff does this via the |
| 464 | `TimeZone` type, which can be a fixed offset, a POSIX time zone or TZif-backed |
| 465 | (usually from the [IANA Time Zone Database]). |
| 466 | |
| 467 | |
| 468 | ## Why doesn't Jiff support leap seconds? |
| 469 | |
| 470 | The short summary is that the use cases for leap second support are rather |
| 471 | limited, and the effect they have on overall API complexity is quite large. |
| 472 | That is, I believe they would make the API of Jiff more complicated than the |
| 473 | value they bring to the domain. |
| 474 | |
| 475 | A standard work-around for _part_ of the leap second problem---and usually the |
| 476 | one people care about---is to use custom TZif data that describes when each of |
| 477 | the leap seconds occurs. In effect, you can treat [TAI] as its own time zone. |
| 478 | This enables callers to compute accurate durations of time that span a leap |
| 479 | second (positive or negative). And indeed, so long as you build that TZif |
| 480 | data, Jiff supports this via `TimeZone::tzif`. |
| 481 | |
| 482 | I wrote a lot more [about leap seconds on the issue |
| 483 | tracker][github-issue-leap]. |
| 484 | |
| 485 | |
| 486 | ## Why isn't there any integration with `std::time::Duration`? |
| 487 | |
| 488 | The initial release of `jiff 0.1` originally left out any integration |
| 489 | points with `std::time::Duration`. Since then, `SignedDuration` has |
| 490 | been added to Jiff. And `TryFrom` trait implementations have been added |
| 491 | to both `SignedDuration` and `Span` to make conversions between it and |
| 492 | `std::time::Duration` easier. |
| 493 | |
| 494 | |
| 495 | ## What are the `ZoneDifference` and `ZonedRound` types for? |
| 496 | |
| 497 | The `ZonedDifference` and `ZonedRound` are builders for expressing the |
| 498 | parameters to the functions `Zoned::{since, until}` and `Zoned::round`, |
| 499 | respectively. For example, this: |
| 500 | |
| 501 | ```rust |
| 502 | use jiff::{civil::date, ToSpan}; |
| 503 | |
| 504 | let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 505 | let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 506 | assert_eq!(zdt1.until(&zdt2)?, 744.hours().seconds(36).fieldwise()); |
| 507 | |
| 508 | # Ok::<(), Box<dyn std::error::Error>>(()) |
| 509 | ``` |
| 510 | |
| 511 | Is equivalent to: |
| 512 | |
| 513 | ```rust |
| 514 | use jiff::{civil::date, ToSpan, ZonedDifference}; |
| 515 | |
| 516 | let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 517 | let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 518 | assert_eq!( |
| 519 | zdt1.until(ZonedDifference::new(&zdt2))?, |
| 520 | 744.hours().seconds(36).fieldwise(), |
| 521 | ); |
| 522 | |
| 523 | # Ok::<(), Box<dyn std::error::Error>>(()) |
| 524 | ``` |
| 525 | |
| 526 | The point of this is that `ZonedDifference` permits specifying additional |
| 527 | configuration. For example, rounding the span returned: |
| 528 | |
| 529 | ```rust |
| 530 | use jiff::{civil::date, ToSpan, Unit, ZonedDifference}; |
| 531 | |
| 532 | let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 533 | let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 534 | assert_eq!( |
| 535 | zdt1.until(ZonedDifference::new(&zdt2).smallest(Unit::Minute))?, |
| 536 | 744.hours().fieldwise(), |
| 537 | ); |
| 538 | |
| 539 | # Ok::<(), Box<dyn std::error::Error>>(()) |
| 540 | ``` |
| 541 | |
| 542 | By using a dedicated type to represent the parameters, we can enable ergonomic |
| 543 | uses of the API for common cases (by using `From<&Zoned> for ZonedDifference` |
| 544 | trait implementations) while still permitting callers to provide additional |
| 545 | configuration. |
| 546 | |
| 547 | An alternative API would be to remove the additional parameters to |
| 548 | `Zoned::until`, and instead require callers to do span rounding themselves |
| 549 | explicitly. But this is more verbose and requires repeating the correct |
| 550 | zoned datetime to indicate how to interpret non-uniform units. For example, |
| 551 | instead of this: |
| 552 | |
| 553 | ```rust |
| 554 | use jiff::{civil::date, ToSpan, Unit, ZonedDifference}; |
| 555 | |
| 556 | let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 557 | let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 558 | let diff = ZonedDifference::new(&zdt2) |
| 559 | .largest(Unit::Month) |
| 560 | .smallest(Unit::Minute); |
| 561 | assert_eq!(zdt1.until(diff)?, 1.month().fieldwise()); |
| 562 | |
| 563 | # Ok::<(), Box<dyn std::error::Error>>(()) |
| 564 | ``` |
| 565 | |
| 566 | One would need to do this: |
| 567 | |
| 568 | ```rust |
| 569 | use jiff::{civil::date, RoundMode, SpanRound, ToSpan, Unit}; |
| 570 | |
| 571 | let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 572 | let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 573 | let span = zdt1.until(&zdt2)?; |
| 574 | let rounded = span.round( |
| 575 | SpanRound::new() |
| 576 | .largest(Unit::Month) |
| 577 | .smallest(Unit::Minute) |
| 578 | .relative(&zdt1) |
| 579 | .mode(RoundMode::Trunc), |
| 580 | )?; |
| 581 | assert_eq!(rounded, 1.month().fieldwise()); |
| 582 | |
| 583 | # Ok::<(), Box<dyn std::error::Error>>(()) |
| 584 | ``` |
| 585 | |
| 586 | This is somewhat fiddly and easy to get wrong. Moreover, the `Zoned::until` |
| 587 | API, when rounding is enabled, will automatically use `RoundMode::Trunc`, since |
| 588 | this is what usually expects when computing the span between two datetimes. But |
| 589 | span rounding uses `RoundMode::HalfExpand` by default, corresponding to how you |
| 590 | were likely taught to round in school. (Rounds to the nearest unit, with ties |
| 591 | breaking away from zero.) |
| 592 | |
| 593 | Similar reasoning applies to other "parameter builder" types like |
| 594 | `civil::DateTimeDifference` as well. |
| 595 | |
| 596 | |
| 597 | ## Why isn't `Timestamp` called `Instant`? |
| 598 | |
| 599 | The main reason why is because of the existence of `std::time::Instant`. While |
| 600 | that doesn't in and of itself prevent Jiff from using the name `Instant`, it |
| 601 | creates a naming clash with something that is _similar_ but different. Namely, |
| 602 | a Jiff `Timestamp` corresponds to a time from your system clock, where as an |
| 603 | `Instant` represents _monotonic_ time. The system clock might change or even |
| 604 | go backwards, where as a monotonic instant will always produce time that is |
| 605 | greater than or equal to a previous time. |
| 606 | |
| 607 | An `Instant` is, for example, something you might use to measure the time |
| 608 | something takes in a program. Like in capturing a measurement for a benchmark. |
| 609 | Conversely, a `Timestamp` is something you use to represent time as represented |
| 610 | by the system. In particular, a `Timestamp` is like a `std::time::SystemTime` |
| 611 | and _not_ a `std::time::Instant`. |
| 612 | |
| 613 | While [Temporal] uses the name `Instant` for their equivalent of Jiff's |
| 614 | `Timestamp` type, using the name `Instant` in Jiff would likely result in |
| 615 | serious confusion and conflicts in names when someone wants to use both an |
| 616 | `Instant` and a `Timestamp` in the same namespace. |
| 617 | |
| 618 | [Temporal]: https://tc39.es/proposal-temporal/docs/ |
| 619 | [temporal-one-duration]: https://github.com/tc39/proposal-temporal/issues/2915 |
| 620 | [comparison]: http://docs.rs/jiff/*/jiff/_documentation/comparison/index.html |
| 621 | [comparison-chrono]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#chrono-v0438 |
| 622 | [comparison-time]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#time-v0336 |
| 623 | [comparison-hifitime]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#hifitime-v0390 |
| 624 | [comparison-icu]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#icu-v150 |
| 625 | [RFC 8536]: https://datatracker.ietf.org/doc/draft-murchison-rfc8536bis/ |
| 626 | [RFC 9557]: https://datatracker.ietf.org/doc/rfc9557/ |
| 627 | [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html |
| 628 | [IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database |
| 629 | [TAI]: https://en.wikipedia.org/wiki/International_Atomic_Time |
| 630 | [github-issue-leap]: https://github.com/BurntSushi/jiff/issues/7 |
| 631 | [`java.time`]: https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html |
| 632 | [NodaTime]: https://nodatime.org/ |
| 633 | [`chrono-tz`]: https://docs.rs/chrono-tz |
| 634 | [`tzfile`]: https://docs.rs/tzfile |
| 635 | [`chrono`]: https://docs.rs/chrono |
| 636 | [`time`]: https://docs.rs/time |
| 637 | [`hifitime`]: https://docs.rs/hifitime |
| 638 | [`icu`]: https://docs.rs/icu |