1 | //! # Chrono: Date and Time for Rust |
2 | //! |
3 | //! Chrono aims to provide all functionality needed to do correct operations on dates and times in |
4 | //! the [proleptic Gregorian calendar]: |
5 | //! |
6 | //! * The [`DateTime`] type is timezone-aware by default, with separate timezone-naive types. |
7 | //! * Operations that may produce an invalid or ambiguous date and time return `Option` or |
8 | //! [`MappedLocalTime`]. |
9 | //! * Configurable parsing and formatting with a `strftime` inspired date and time formatting |
10 | //! syntax. |
11 | //! * The [`Local`] timezone works with the current timezone of the OS. |
12 | //! * Types and operations are implemented to be reasonably efficient. |
13 | //! |
14 | //! Timezone data is not shipped with chrono by default to limit binary sizes. Use the companion |
15 | //! crate [Chrono-TZ] or [`tzfile`] for full timezone support. |
16 | //! |
17 | //! [proleptic Gregorian calendar]: https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar |
18 | //! [Chrono-TZ]: https://crates.io/crates/chrono-tz |
19 | //! [`tzfile`]: https://crates.io/crates/tzfile |
20 | //! |
21 | //! ### Features |
22 | //! |
23 | //! Chrono supports various runtime environments and operating systems, and has several features |
24 | //! that may be enabled or disabled. |
25 | //! |
26 | //! Default features: |
27 | //! |
28 | //! - `alloc`: Enable features that depend on allocation (primarily string formatting). |
29 | //! - `std`: Enables functionality that depends on the standard library. This is a superset of |
30 | //! `alloc` and adds interoperation with standard library types and traits. |
31 | //! - `clock`: Enables reading the local timezone (`Local`). This is a superset of `now`. |
32 | //! - `now`: Enables reading the system time (`now`). |
33 | //! - `wasmbind`: Interface with the JS Date API for the `wasm32` target. |
34 | //! |
35 | //! Optional features: |
36 | //! |
37 | //! - `serde`: Enable serialization/deserialization via [serde]. |
38 | //! - `rkyv`: Deprecated, use the `rkyv-*` features. |
39 | //! - `rkyv-16`: Enable serialization/deserialization via [rkyv], |
40 | //! using 16-bit integers for integral `*size` types. |
41 | //! - `rkyv-32`: Enable serialization/deserialization via [rkyv], |
42 | //! using 32-bit integers for integral `*size` types. |
43 | //! - `rkyv-64`: Enable serialization/deserialization via [rkyv], |
44 | //! using 64-bit integers for integral `*size` types. |
45 | //! - `rkyv-validation`: Enable rkyv validation support using `bytecheck`. |
46 | //! - `arbitrary`: Construct arbitrary instances of a type with the Arbitrary crate. |
47 | //! - `unstable-locales`: Enable localization. This adds various methods with a `_localized` suffix. |
48 | //! The implementation and API may change or even be removed in a patch release. Feedback welcome. |
49 | //! - `oldtime`: This feature no longer has any effect; it used to offer compatibility with the |
50 | //! `time` 0.1 crate. |
51 | //! |
52 | //! Note: The `rkyv{,-16,-32,-64}` features are mutually exclusive. |
53 | //! |
54 | //! See the [cargo docs] for examples of specifying features. |
55 | //! |
56 | //! [serde]: https://github.com/serde-rs/serde |
57 | //! [rkyv]: https://github.com/rkyv/rkyv |
58 | //! [cargo docs]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#choosing-features |
59 | //! |
60 | //! ## Overview |
61 | //! |
62 | //! ### Time delta / Duration |
63 | //! |
64 | //! Chrono has a [`TimeDelta`] type to represent the magnitude of a time span. This is an "accurate" |
65 | //! duration represented as seconds and nanoseconds, and does not represent "nominal" components |
66 | //! such as days or months. |
67 | //! |
68 | //! The [`TimeDelta`] type was previously named `Duration` (and is still available as a type alias |
69 | //! with that name). A notable difference with the similar [`core::time::Duration`] is that it is a |
70 | //! signed value instead of unsigned. |
71 | //! |
72 | //! Chrono currently only supports a small number of operations with [`core::time::Duration`]. |
73 | //! You can convert between both types with the [`TimeDelta::from_std`] and [`TimeDelta::to_std`] |
74 | //! methods. |
75 | //! |
76 | //! ### Date and Time |
77 | //! |
78 | //! Chrono provides a [`DateTime`] type to represent a date and a time in a timezone. |
79 | //! |
80 | //! For more abstract moment-in-time tracking such as internal timekeeping that is unconcerned with |
81 | //! timezones, consider [`std::time::SystemTime`], which tracks your system clock, or |
82 | //! [`std::time::Instant`], which is an opaque but monotonically-increasing representation of a |
83 | //! moment in time. |
84 | //! |
85 | //! [`DateTime`] is timezone-aware and must be constructed from a [`TimeZone`] object, which defines |
86 | //! how the local date is converted to and back from the UTC date. |
87 | //! There are three well-known [`TimeZone`] implementations: |
88 | //! |
89 | //! * [`Utc`] specifies the UTC time zone. It is most efficient. |
90 | //! |
91 | //! * [`Local`] specifies the system local time zone. |
92 | //! |
93 | //! * [`FixedOffset`] specifies an arbitrary, fixed time zone such as UTC+09:00 or UTC-10:30. |
94 | //! This often results from the parsed textual date and time. Since it stores the most information |
95 | //! and does not depend on the system environment, you would want to normalize other `TimeZone`s |
96 | //! into this type. |
97 | //! |
98 | //! [`DateTime`]s with different [`TimeZone`] types are distinct and do not mix, but can be |
99 | //! converted to each other using the [`DateTime::with_timezone`] method. |
100 | //! |
101 | //! You can get the current date and time in the UTC time zone ([`Utc::now()`]) or in the local time |
102 | //! zone ([`Local::now()`]). |
103 | //! |
104 | //! ``` |
105 | //! # #[cfg (feature = "now" )] { |
106 | //! use chrono::prelude::*; |
107 | //! |
108 | //! let utc: DateTime<Utc> = Utc::now(); // e.g. `2014-11-28T12:45:59.324310806Z` |
109 | //! # let _ = utc; |
110 | //! # } |
111 | //! ``` |
112 | //! |
113 | //! ``` |
114 | //! # #[cfg (feature = "clock" )] { |
115 | //! use chrono::prelude::*; |
116 | //! |
117 | //! let local: DateTime<Local> = Local::now(); // e.g. `2014-11-28T21:45:59.324310806+09:00` |
118 | //! # let _ = local; |
119 | //! # } |
120 | //! ``` |
121 | //! |
122 | //! Alternatively, you can create your own date and time. This is a bit verbose due to Rust's lack |
123 | //! of function and method overloading, but in turn we get a rich combination of initialization |
124 | //! methods. |
125 | //! |
126 | //! ``` |
127 | //! use chrono::offset::MappedLocalTime; |
128 | //! use chrono::prelude::*; |
129 | //! |
130 | //! # fn doctest() -> Option<()> { |
131 | //! |
132 | //! let dt = Utc.with_ymd_and_hms(2014, 7, 8, 9, 10, 11).unwrap(); // `2014-07-08T09:10:11Z` |
133 | //! assert_eq!( |
134 | //! dt, |
135 | //! NaiveDate::from_ymd_opt(2014, 7, 8)? |
136 | //! .and_hms_opt(9, 10, 11)? |
137 | //! .and_utc() |
138 | //! ); |
139 | //! |
140 | //! // July 8 is 188th day of the year 2014 (`o` for "ordinal") |
141 | //! assert_eq!(dt, NaiveDate::from_yo_opt(2014, 189)?.and_hms_opt(9, 10, 11)?.and_utc()); |
142 | //! // July 8 is Tuesday in ISO week 28 of the year 2014. |
143 | //! assert_eq!( |
144 | //! dt, |
145 | //! NaiveDate::from_isoywd_opt(2014, 28, Weekday::Tue)?.and_hms_opt(9, 10, 11)?.and_utc() |
146 | //! ); |
147 | //! |
148 | //! let dt = NaiveDate::from_ymd_opt(2014, 7, 8)? |
149 | //! .and_hms_milli_opt(9, 10, 11, 12)? |
150 | //! .and_utc(); // `2014-07-08T09:10:11.012Z` |
151 | //! assert_eq!( |
152 | //! dt, |
153 | //! NaiveDate::from_ymd_opt(2014, 7, 8)? |
154 | //! .and_hms_micro_opt(9, 10, 11, 12_000)? |
155 | //! .and_utc() |
156 | //! ); |
157 | //! assert_eq!( |
158 | //! dt, |
159 | //! NaiveDate::from_ymd_opt(2014, 7, 8)? |
160 | //! .and_hms_nano_opt(9, 10, 11, 12_000_000)? |
161 | //! .and_utc() |
162 | //! ); |
163 | //! |
164 | //! // dynamic verification |
165 | //! assert_eq!( |
166 | //! Utc.with_ymd_and_hms(2014, 7, 8, 21, 15, 33), |
167 | //! MappedLocalTime::Single( |
168 | //! NaiveDate::from_ymd_opt(2014, 7, 8)?.and_hms_opt(21, 15, 33)?.and_utc() |
169 | //! ) |
170 | //! ); |
171 | //! assert_eq!(Utc.with_ymd_and_hms(2014, 7, 8, 80, 15, 33), MappedLocalTime::None); |
172 | //! assert_eq!(Utc.with_ymd_and_hms(2014, 7, 38, 21, 15, 33), MappedLocalTime::None); |
173 | //! |
174 | //! # #[cfg (feature = "clock" )] { |
175 | //! // other time zone objects can be used to construct a local datetime. |
176 | //! // obviously, `local_dt` is normally different from `dt`, but `fixed_dt` should be identical. |
177 | //! let local_dt = Local |
178 | //! .from_local_datetime( |
179 | //! &NaiveDate::from_ymd_opt(2014, 7, 8).unwrap().and_hms_milli_opt(9, 10, 11, 12).unwrap(), |
180 | //! ) |
181 | //! .unwrap(); |
182 | //! let fixed_dt = FixedOffset::east_opt(9 * 3600) |
183 | //! .unwrap() |
184 | //! .from_local_datetime( |
185 | //! &NaiveDate::from_ymd_opt(2014, 7, 8) |
186 | //! .unwrap() |
187 | //! .and_hms_milli_opt(18, 10, 11, 12) |
188 | //! .unwrap(), |
189 | //! ) |
190 | //! .unwrap(); |
191 | //! assert_eq!(dt, fixed_dt); |
192 | //! # let _ = local_dt; |
193 | //! # } |
194 | //! # Some(()) |
195 | //! # } |
196 | //! # doctest().unwrap(); |
197 | //! ``` |
198 | //! |
199 | //! Various properties are available to the date and time, and can be altered individually. Most of |
200 | //! them are defined in the traits [`Datelike`] and [`Timelike`] which you should `use` before. |
201 | //! Addition and subtraction is also supported. |
202 | //! The following illustrates most supported operations to the date and time: |
203 | //! |
204 | //! ```rust |
205 | //! use chrono::prelude::*; |
206 | //! use chrono::TimeDelta; |
207 | //! |
208 | //! // assume this returned `2014-11-28T21:45:59.324310806+09:00`: |
209 | //! let dt = FixedOffset::east_opt(9 * 3600) |
210 | //! .unwrap() |
211 | //! .from_local_datetime( |
212 | //! &NaiveDate::from_ymd_opt(2014, 11, 28) |
213 | //! .unwrap() |
214 | //! .and_hms_nano_opt(21, 45, 59, 324310806) |
215 | //! .unwrap(), |
216 | //! ) |
217 | //! .unwrap(); |
218 | //! |
219 | //! // property accessors |
220 | //! assert_eq!((dt.year(), dt.month(), dt.day()), (2014, 11, 28)); |
221 | //! assert_eq!((dt.month0(), dt.day0()), (10, 27)); // for unfortunate souls |
222 | //! assert_eq!((dt.hour(), dt.minute(), dt.second()), (21, 45, 59)); |
223 | //! assert_eq!(dt.weekday(), Weekday::Fri); |
224 | //! assert_eq!(dt.weekday().number_from_monday(), 5); // Mon=1, ..., Sun=7 |
225 | //! assert_eq!(dt.ordinal(), 332); // the day of year |
226 | //! assert_eq!(dt.num_days_from_ce(), 735565); // the number of days from and including Jan 1, 1 |
227 | //! |
228 | //! // time zone accessor and manipulation |
229 | //! assert_eq!(dt.offset().fix().local_minus_utc(), 9 * 3600); |
230 | //! assert_eq!(dt.timezone(), FixedOffset::east_opt(9 * 3600).unwrap()); |
231 | //! assert_eq!( |
232 | //! dt.with_timezone(&Utc), |
233 | //! NaiveDate::from_ymd_opt(2014, 11, 28) |
234 | //! .unwrap() |
235 | //! .and_hms_nano_opt(12, 45, 59, 324310806) |
236 | //! .unwrap() |
237 | //! .and_utc() |
238 | //! ); |
239 | //! |
240 | //! // a sample of property manipulations (validates dynamically) |
241 | //! assert_eq!(dt.with_day(29).unwrap().weekday(), Weekday::Sat); // 2014-11-29 is Saturday |
242 | //! assert_eq!(dt.with_day(32), None); |
243 | //! assert_eq!(dt.with_year(-300).unwrap().num_days_from_ce(), -109606); // November 29, 301 BCE |
244 | //! |
245 | //! // arithmetic operations |
246 | //! let dt1 = Utc.with_ymd_and_hms(2014, 11, 14, 8, 9, 10).unwrap(); |
247 | //! let dt2 = Utc.with_ymd_and_hms(2014, 11, 14, 10, 9, 8).unwrap(); |
248 | //! assert_eq!(dt1.signed_duration_since(dt2), TimeDelta::try_seconds(-2 * 3600 + 2).unwrap()); |
249 | //! assert_eq!(dt2.signed_duration_since(dt1), TimeDelta::try_seconds(2 * 3600 - 2).unwrap()); |
250 | //! assert_eq!( |
251 | //! Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap() |
252 | //! + TimeDelta::try_seconds(1_000_000_000).unwrap(), |
253 | //! Utc.with_ymd_and_hms(2001, 9, 9, 1, 46, 40).unwrap() |
254 | //! ); |
255 | //! assert_eq!( |
256 | //! Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap() |
257 | //! - TimeDelta::try_seconds(1_000_000_000).unwrap(), |
258 | //! Utc.with_ymd_and_hms(1938, 4, 24, 22, 13, 20).unwrap() |
259 | //! ); |
260 | //! ``` |
261 | //! |
262 | //! ### Formatting and Parsing |
263 | //! |
264 | //! Formatting is done via the [`format`](DateTime::format()) method, which format is equivalent to |
265 | //! the familiar `strftime` format. |
266 | //! |
267 | //! See [`format::strftime`](format::strftime#specifiers) documentation for full syntax and list of |
268 | //! specifiers. |
269 | //! |
270 | //! The default `to_string` method and `{:?}` specifier also give a reasonable representation. |
271 | //! Chrono also provides [`to_rfc2822`](DateTime::to_rfc2822) and |
272 | //! [`to_rfc3339`](DateTime::to_rfc3339) methods for well-known formats. |
273 | //! |
274 | //! Chrono now also provides date formatting in almost any language without the help of an |
275 | //! additional C library. This functionality is under the feature `unstable-locales`: |
276 | //! |
277 | //! ```toml |
278 | //! chrono = { version = "0.4", features = ["unstable-locales"] } |
279 | //! ``` |
280 | //! |
281 | //! The `unstable-locales` feature requires and implies at least the `alloc` feature. |
282 | //! |
283 | //! ```rust |
284 | //! # #[allow (unused_imports)] |
285 | //! use chrono::prelude::*; |
286 | //! |
287 | //! # #[cfg (all(feature = "unstable-locales" , feature = "alloc" ))] |
288 | //! # fn test() { |
289 | //! let dt = Utc.with_ymd_and_hms(2014, 11, 28, 12, 0, 9).unwrap(); |
290 | //! assert_eq!(dt.format("%Y-%m-%d %H:%M:%S" ).to_string(), "2014-11-28 12:00:09" ); |
291 | //! assert_eq!(dt.format("%a %b %e %T %Y" ).to_string(), "Fri Nov 28 12:00:09 2014" ); |
292 | //! assert_eq!( |
293 | //! dt.format_localized("%A %e %B %Y, %T" , Locale::fr_BE).to_string(), |
294 | //! "vendredi 28 novembre 2014, 12:00:09" |
295 | //! ); |
296 | //! |
297 | //! assert_eq!(dt.format("%a %b %e %T %Y" ).to_string(), dt.format("%c" ).to_string()); |
298 | //! assert_eq!(dt.to_string(), "2014-11-28 12:00:09 UTC" ); |
299 | //! assert_eq!(dt.to_rfc2822(), "Fri, 28 Nov 2014 12:00:09 +0000" ); |
300 | //! assert_eq!(dt.to_rfc3339(), "2014-11-28T12:00:09+00:00" ); |
301 | //! assert_eq!(format!("{:?}" , dt), "2014-11-28T12:00:09Z" ); |
302 | //! |
303 | //! // Note that milli/nanoseconds are only printed if they are non-zero |
304 | //! let dt_nano = NaiveDate::from_ymd_opt(2014, 11, 28) |
305 | //! .unwrap() |
306 | //! .and_hms_nano_opt(12, 0, 9, 1) |
307 | //! .unwrap() |
308 | //! .and_utc(); |
309 | //! assert_eq!(format!("{:?}" , dt_nano), "2014-11-28T12:00:09.000000001Z" ); |
310 | //! # } |
311 | //! # #[cfg (not(all(feature = "unstable-locales" , feature = "alloc" )))] |
312 | //! # fn test() {} |
313 | //! # if cfg!(all(feature = "unstable-locales" , feature = "alloc" )) { |
314 | //! # test(); |
315 | //! # } |
316 | //! ``` |
317 | //! |
318 | //! Parsing can be done with two methods: |
319 | //! |
320 | //! 1. The standard [`FromStr`](std::str::FromStr) trait (and [`parse`](str::parse) method on a |
321 | //! string) can be used for parsing `DateTime<FixedOffset>`, `DateTime<Utc>` and |
322 | //! `DateTime<Local>` values. This parses what the `{:?}` ([`std::fmt::Debug`] format specifier |
323 | //! prints, and requires the offset to be present. |
324 | //! |
325 | //! 2. [`DateTime::parse_from_str`] parses a date and time with offsets and returns |
326 | //! `DateTime<FixedOffset>`. This should be used when the offset is a part of input and the |
327 | //! caller cannot guess that. It *cannot* be used when the offset can be missing. |
328 | //! [`DateTime::parse_from_rfc2822`] and [`DateTime::parse_from_rfc3339`] are similar but for |
329 | //! well-known formats. |
330 | //! |
331 | //! More detailed control over the parsing process is available via [`format`](mod@format) module. |
332 | //! |
333 | //! ```rust |
334 | //! use chrono::prelude::*; |
335 | //! |
336 | //! let dt = Utc.with_ymd_and_hms(2014, 11, 28, 12, 0, 9).unwrap(); |
337 | //! let fixed_dt = dt.with_timezone(&FixedOffset::east_opt(9 * 3600).unwrap()); |
338 | //! |
339 | //! // method 1 |
340 | //! assert_eq!("2014-11-28T12:00:09Z" .parse::<DateTime<Utc>>(), Ok(dt.clone())); |
341 | //! assert_eq!("2014-11-28T21:00:09+09:00" .parse::<DateTime<Utc>>(), Ok(dt.clone())); |
342 | //! assert_eq!("2014-11-28T21:00:09+09:00" .parse::<DateTime<FixedOffset>>(), Ok(fixed_dt.clone())); |
343 | //! |
344 | //! // method 2 |
345 | //! assert_eq!( |
346 | //! DateTime::parse_from_str("2014-11-28 21:00:09 +09:00" , "%Y-%m-%d %H:%M:%S %z" ), |
347 | //! Ok(fixed_dt.clone()) |
348 | //! ); |
349 | //! assert_eq!( |
350 | //! DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900" ), |
351 | //! Ok(fixed_dt.clone()) |
352 | //! ); |
353 | //! assert_eq!(DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00" ), Ok(fixed_dt.clone())); |
354 | //! |
355 | //! // oops, the year is missing! |
356 | //! assert!(DateTime::parse_from_str("Fri Nov 28 12:00:09" , "%a %b %e %T %Y" ).is_err()); |
357 | //! // oops, the format string does not include the year at all! |
358 | //! assert!(DateTime::parse_from_str("Fri Nov 28 12:00:09" , "%a %b %e %T" ).is_err()); |
359 | //! // oops, the weekday is incorrect! |
360 | //! assert!(DateTime::parse_from_str("Sat Nov 28 12:00:09 2014" , "%a %b %e %T %Y" ).is_err()); |
361 | //! ``` |
362 | //! |
363 | //! Again: See [`format::strftime`](format::strftime#specifiers) documentation for full syntax and |
364 | //! list of specifiers. |
365 | //! |
366 | //! ### Conversion from and to EPOCH timestamps |
367 | //! |
368 | //! Use [`DateTime::from_timestamp(seconds, nanoseconds)`](DateTime::from_timestamp) |
369 | //! to construct a [`DateTime<Utc>`] from a UNIX timestamp |
370 | //! (seconds, nanoseconds that passed since January 1st 1970). |
371 | //! |
372 | //! Use [`DateTime.timestamp`](DateTime::timestamp) to get the timestamp (in seconds) |
373 | //! from a [`DateTime`]. Additionally, you can use |
374 | //! [`DateTime.timestamp_subsec_nanos`](DateTime::timestamp_subsec_nanos) |
375 | //! to get the number of additional number of nanoseconds. |
376 | //! |
377 | //! ``` |
378 | //! # #[cfg (feature = "alloc" )] { |
379 | //! // We need the trait in scope to use Utc::timestamp(). |
380 | //! use chrono::{DateTime, Utc}; |
381 | //! |
382 | //! // Construct a datetime from epoch: |
383 | //! let dt: DateTime<Utc> = DateTime::from_timestamp(1_500_000_000, 0).unwrap(); |
384 | //! assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000" ); |
385 | //! |
386 | //! // Get epoch value from a datetime: |
387 | //! let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000" ).unwrap(); |
388 | //! assert_eq!(dt.timestamp(), 1_500_000_000); |
389 | //! # } |
390 | //! ``` |
391 | //! |
392 | //! ### Naive date and time |
393 | //! |
394 | //! Chrono provides naive counterparts to `Date`, (non-existent) `Time` and `DateTime` as |
395 | //! [`NaiveDate`], [`NaiveTime`] and [`NaiveDateTime`] respectively. |
396 | //! |
397 | //! They have almost equivalent interfaces as their timezone-aware twins, but are not associated to |
398 | //! time zones obviously and can be quite low-level. They are mostly useful for building blocks for |
399 | //! higher-level types. |
400 | //! |
401 | //! Timezone-aware `DateTime` and `Date` types have two methods returning naive versions: |
402 | //! [`naive_local`](DateTime::naive_local) returns a view to the naive local time, |
403 | //! and [`naive_utc`](DateTime::naive_utc) returns a view to the naive UTC time. |
404 | //! |
405 | //! ## Limitations |
406 | //! |
407 | //! * Only the proleptic Gregorian calendar (i.e. extended to support older dates) is supported. |
408 | //! * Date types are limited to about +/- 262,000 years from the common epoch. |
409 | //! * Time types are limited to nanosecond accuracy. |
410 | //! * Leap seconds can be represented, but Chrono does not fully support them. |
411 | //! See [Leap Second Handling](NaiveTime#leap-second-handling). |
412 | //! |
413 | //! ## Rust version requirements |
414 | //! |
415 | //! The Minimum Supported Rust Version (MSRV) is currently **Rust 1.61.0**. |
416 | //! |
417 | //! The MSRV is explicitly tested in CI. It may be bumped in minor releases, but this is not done |
418 | //! lightly. |
419 | //! |
420 | //! ## Relation between chrono and time 0.1 |
421 | //! |
422 | //! Rust first had a `time` module added to `std` in its 0.7 release. It later moved to |
423 | //! `libextra`, and then to a `libtime` library shipped alongside the standard library. In 2014 |
424 | //! work on chrono started in order to provide a full-featured date and time library in Rust. |
425 | //! Some improvements from chrono made it into the standard library; notably, `chrono::Duration` |
426 | //! was included as `std::time::Duration` ([rust#15934]) in 2014. |
427 | //! |
428 | //! In preparation of Rust 1.0 at the end of 2014 `libtime` was moved out of the Rust distro and |
429 | //! into the `time` crate to eventually be redesigned ([rust#18832], [rust#18858]), like the |
430 | //! `num` and `rand` crates. Of course chrono kept its dependency on this `time` crate. `time` |
431 | //! started re-exporting `std::time::Duration` during this period. Later, the standard library was |
432 | //! changed to have a more limited unsigned `Duration` type ([rust#24920], [RFC 1040]), while the |
433 | //! `time` crate kept the full functionality with `time::Duration`. `time::Duration` had been a |
434 | //! part of chrono's public API. |
435 | //! |
436 | //! By 2016 `time` 0.1 lived under the `rust-lang-deprecated` organisation and was not actively |
437 | //! maintained ([time#136]). chrono absorbed the platform functionality and `Duration` type of the |
438 | //! `time` crate in [chrono#478] (the work started in [chrono#286]). In order to preserve |
439 | //! compatibility with downstream crates depending on `time` and `chrono` sharing a `Duration` |
440 | //! type, chrono kept depending on time 0.1. chrono offered the option to opt out of the `time` |
441 | //! dependency by disabling the `oldtime` feature (swapping it out for an effectively similar |
442 | //! chrono type). In 2019, @jhpratt took over maintenance on the `time` crate and released what |
443 | //! amounts to a new crate as `time` 0.2. |
444 | //! |
445 | //! [rust#15934]: https://github.com/rust-lang/rust/pull/15934 |
446 | //! [rust#18832]: https://github.com/rust-lang/rust/pull/18832#issuecomment-62448221 |
447 | //! [rust#18858]: https://github.com/rust-lang/rust/pull/18858 |
448 | //! [rust#24920]: https://github.com/rust-lang/rust/pull/24920 |
449 | //! [RFC 1040]: https://rust-lang.github.io/rfcs/1040-duration-reform.html |
450 | //! [time#136]: https://github.com/time-rs/time/issues/136 |
451 | //! [chrono#286]: https://github.com/chronotope/chrono/pull/286 |
452 | //! [chrono#478]: https://github.com/chronotope/chrono/pull/478 |
453 | //! |
454 | //! ## Security advisories |
455 | //! |
456 | //! In November of 2020 [CVE-2020-26235] and [RUSTSEC-2020-0071] were opened against the `time` crate. |
457 | //! @quininer had found that calls to `localtime_r` may be unsound ([chrono#499]). Eventually, almost |
458 | //! a year later, this was also made into a security advisory against chrono as [RUSTSEC-2020-0159], |
459 | //! which had platform code similar to `time`. |
460 | //! |
461 | //! On Unix-like systems a process is given a timezone id or description via the `TZ` environment |
462 | //! variable. We need this timezone data to calculate the current local time from a value that is |
463 | //! in UTC, such as the time from the system clock. `time` 0.1 and chrono used the POSIX function |
464 | //! `localtime_r` to do the conversion to local time, which reads the `TZ` variable. |
465 | //! |
466 | //! Rust assumes the environment to be writable and uses locks to access it from multiple threads. |
467 | //! Some other programming languages and libraries use similar locking strategies, but these are |
468 | //! typically not shared across languages. More importantly, POSIX declares modifying the |
469 | //! environment in a multi-threaded process as unsafe, and `getenv` in libc can't be changed to |
470 | //! take a lock because it returns a pointer to the data (see [rust#27970] for more discussion). |
471 | //! |
472 | //! Since version 4.20 chrono no longer uses `localtime_r`, instead using Rust code to query the |
473 | //! timezone (from the `TZ` variable or via `iana-time-zone` as a fallback) and work with data |
474 | //! from the system timezone database directly. The code for this was forked from the [tz-rs crate] |
475 | //! by @x-hgg-x. As such, chrono now respects the Rust lock when reading the `TZ` environment |
476 | //! variable. In general, code should avoid modifying the environment. |
477 | //! |
478 | //! [CVE-2020-26235]: https://nvd.nist.gov/vuln/detail/CVE-2020-26235 |
479 | //! [RUSTSEC-2020-0071]: https://rustsec.org/advisories/RUSTSEC-2020-0071 |
480 | //! [chrono#499]: https://github.com/chronotope/chrono/pull/499 |
481 | //! [RUSTSEC-2020-0159]: https://rustsec.org/advisories/RUSTSEC-2020-0159.html |
482 | //! [rust#27970]: https://github.com/rust-lang/rust/issues/27970 |
483 | //! [chrono#677]: https://github.com/chronotope/chrono/pull/677 |
484 | //! [tz-rs crate]: https://crates.io/crates/tz-rs |
485 | //! |
486 | //! ## Removing time 0.1 |
487 | //! |
488 | //! Because time 0.1 has been unmaintained for years, however, the security advisory mentioned |
489 | //! above has not been addressed. While chrono maintainers were careful not to break backwards |
490 | //! compatibility with the `time::Duration` type, there has been a long stream of issues from |
491 | //! users inquiring about the time 0.1 dependency with the vulnerability. We investigated the |
492 | //! potential breakage of removing the time 0.1 dependency in [chrono#1095] using a crater-like |
493 | //! experiment and determined that the potential for breaking (public) dependencies is very low. |
494 | //! We reached out to those few crates that did still depend on compatibility with time 0.1. |
495 | //! |
496 | //! As such, for chrono 0.4.30 we have decided to swap out the time 0.1 `Duration` implementation |
497 | //! for a local one that will offer a strict superset of the existing API going forward. This |
498 | //! will prevent most downstream users from being affected by the security vulnerability in time |
499 | //! 0.1 while minimizing the ecosystem impact of semver-incompatible version churn. |
500 | //! |
501 | //! [chrono#1095]: https://github.com/chronotope/chrono/pull/1095 |
502 | |
503 | #![doc (html_root_url = "https://docs.rs/chrono/latest/" , test(attr(deny(warnings))))] |
504 | #![deny (missing_docs)] |
505 | #![deny (missing_debug_implementations)] |
506 | #![warn (unreachable_pub)] |
507 | #![deny (clippy::tests_outside_test_module)] |
508 | #![cfg_attr (not(any(feature = "std" , test)), no_std)] |
509 | #![cfg_attr (docsrs, feature(doc_auto_cfg))] |
510 | |
511 | #[cfg (feature = "alloc" )] |
512 | extern crate alloc; |
513 | |
514 | mod time_delta; |
515 | #[cfg (feature = "std" )] |
516 | #[doc (no_inline)] |
517 | pub use time_delta::OutOfRangeError; |
518 | pub use time_delta::TimeDelta; |
519 | |
520 | /// Alias of [`TimeDelta`]. |
521 | pub type Duration = TimeDelta; |
522 | |
523 | use core::fmt; |
524 | |
525 | /// A convenience module appropriate for glob imports (`use chrono::prelude::*;`). |
526 | pub mod prelude { |
527 | #[allow (deprecated)] |
528 | pub use crate::Date; |
529 | #[cfg (feature = "clock" )] |
530 | pub use crate::Local; |
531 | #[cfg (all(feature = "unstable-locales" , feature = "alloc" ))] |
532 | pub use crate::Locale; |
533 | pub use crate::SubsecRound; |
534 | pub use crate::{DateTime, SecondsFormat}; |
535 | pub use crate::{Datelike, Month, Timelike, Weekday}; |
536 | pub use crate::{FixedOffset, Utc}; |
537 | pub use crate::{NaiveDate, NaiveDateTime, NaiveTime}; |
538 | pub use crate::{Offset, TimeZone}; |
539 | } |
540 | |
541 | mod date; |
542 | #[allow (deprecated)] |
543 | pub use date::Date; |
544 | #[doc (no_inline)] |
545 | #[allow (deprecated)] |
546 | pub use date::{MAX_DATE, MIN_DATE}; |
547 | |
548 | mod datetime; |
549 | pub use datetime::DateTime; |
550 | #[allow (deprecated)] |
551 | #[doc (no_inline)] |
552 | pub use datetime::{MAX_DATETIME, MIN_DATETIME}; |
553 | |
554 | pub mod format; |
555 | /// L10n locales. |
556 | #[cfg (feature = "unstable-locales" )] |
557 | pub use format::Locale; |
558 | pub use format::{ParseError, ParseResult, SecondsFormat}; |
559 | |
560 | pub mod naive; |
561 | #[doc (inline)] |
562 | pub use naive::{Days, NaiveDate, NaiveDateTime, NaiveTime}; |
563 | pub use naive::{IsoWeek, NaiveWeek}; |
564 | |
565 | pub mod offset; |
566 | #[cfg (feature = "clock" )] |
567 | #[doc (inline)] |
568 | pub use offset::Local; |
569 | #[doc (hidden)] |
570 | pub use offset::LocalResult; |
571 | pub use offset::MappedLocalTime; |
572 | #[doc (inline)] |
573 | pub use offset::{FixedOffset, Offset, TimeZone, Utc}; |
574 | |
575 | pub mod round; |
576 | pub use round::{DurationRound, RoundingError, SubsecRound}; |
577 | |
578 | mod weekday; |
579 | #[doc (no_inline)] |
580 | pub use weekday::ParseWeekdayError; |
581 | pub use weekday::Weekday; |
582 | |
583 | mod month; |
584 | #[doc (no_inline)] |
585 | pub use month::ParseMonthError; |
586 | pub use month::{Month, Months}; |
587 | |
588 | mod traits; |
589 | pub use traits::{Datelike, Timelike}; |
590 | |
591 | #[cfg (feature = "__internal_bench" )] |
592 | #[doc (hidden)] |
593 | pub use naive::__BenchYearFlags; |
594 | |
595 | /// Serialization/Deserialization with serde |
596 | /// |
597 | /// The [`DateTime`] type has default implementations for (de)serializing to/from the [RFC 3339] |
598 | /// format. This module provides alternatives for serializing to timestamps. |
599 | /// |
600 | /// The alternatives are for use with serde's [`with` annotation] combined with the module name. |
601 | /// Alternatively the individual `serialize` and `deserialize` functions in each module can be used |
602 | /// with serde's [`serialize_with`] and [`deserialize_with`] annotations. |
603 | /// |
604 | /// *Available on crate feature 'serde' only.* |
605 | /// |
606 | /// [RFC 3339]: https://tools.ietf.org/html/rfc3339 |
607 | /// [`with` annotation]: https://serde.rs/field-attrs.html#with |
608 | /// [`serialize_with`]: https://serde.rs/field-attrs.html#serialize_with |
609 | /// [`deserialize_with`]: https://serde.rs/field-attrs.html#deserialize_with |
610 | #[cfg (feature = "serde" )] |
611 | pub mod serde { |
612 | use core::fmt; |
613 | use serde::de; |
614 | |
615 | pub use super::datetime::serde::*; |
616 | |
617 | /// Create a custom `de::Error` with `SerdeError::InvalidTimestamp`. |
618 | pub(crate) fn invalid_ts<E, T>(value: T) -> E |
619 | where |
620 | E: de::Error, |
621 | T: fmt::Display, |
622 | { |
623 | E::custom(SerdeError::InvalidTimestamp(value)) |
624 | } |
625 | |
626 | enum SerdeError<T: fmt::Display> { |
627 | InvalidTimestamp(T), |
628 | } |
629 | |
630 | impl<T: fmt::Display> fmt::Display for SerdeError<T> { |
631 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
632 | match self { |
633 | SerdeError::InvalidTimestamp(ts) => { |
634 | write!(f, "value is not a legal timestamp: {}" , ts) |
635 | } |
636 | } |
637 | } |
638 | } |
639 | } |
640 | |
641 | /// Zero-copy serialization/deserialization with rkyv. |
642 | /// |
643 | /// This module re-exports the `Archived*` versions of chrono's types. |
644 | #[cfg (any(feature = "rkyv" , feature = "rkyv-16" , feature = "rkyv-32" , feature = "rkyv-64" ))] |
645 | pub mod rkyv { |
646 | pub use crate::datetime::ArchivedDateTime; |
647 | pub use crate::month::ArchivedMonth; |
648 | pub use crate::naive::date::ArchivedNaiveDate; |
649 | pub use crate::naive::datetime::ArchivedNaiveDateTime; |
650 | pub use crate::naive::isoweek::ArchivedIsoWeek; |
651 | pub use crate::naive::time::ArchivedNaiveTime; |
652 | pub use crate::offset::fixed::ArchivedFixedOffset; |
653 | #[cfg (feature = "clock" )] |
654 | pub use crate::offset::local::ArchivedLocal; |
655 | pub use crate::offset::utc::ArchivedUtc; |
656 | pub use crate::time_delta::ArchivedTimeDelta; |
657 | pub use crate::weekday::ArchivedWeekday; |
658 | |
659 | /// Alias of [`ArchivedTimeDelta`] |
660 | pub type ArchivedDuration = ArchivedTimeDelta; |
661 | } |
662 | |
663 | /// Out of range error type used in various converting APIs |
664 | #[derive (Clone, Copy, Hash, PartialEq, Eq)] |
665 | pub struct OutOfRange { |
666 | _private: (), |
667 | } |
668 | |
669 | impl OutOfRange { |
670 | const fn new() -> OutOfRange { |
671 | OutOfRange { _private: () } |
672 | } |
673 | } |
674 | |
675 | impl fmt::Display for OutOfRange { |
676 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
677 | write!(f, "out of range" ) |
678 | } |
679 | } |
680 | |
681 | impl fmt::Debug for OutOfRange { |
682 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
683 | write!(f, "out of range" ) |
684 | } |
685 | } |
686 | |
687 | #[cfg (feature = "std" )] |
688 | impl std::error::Error for OutOfRange {} |
689 | |
690 | /// Workaround because `?` is not (yet) available in const context. |
691 | #[macro_export ] |
692 | #[doc (hidden)] |
693 | macro_rules! try_opt { |
694 | ($e:expr) => { |
695 | match $e { |
696 | Some(v) => v, |
697 | None => return None, |
698 | } |
699 | }; |
700 | } |
701 | |
702 | /// Workaround because `.expect()` is not (yet) available in const context. |
703 | pub(crate) const fn expect<T: Copy>(opt: Option<T>, msg: &str) -> T { |
704 | match opt { |
705 | Some(val: T) => val, |
706 | None => panic!("{}" , msg), |
707 | } |
708 | } |
709 | |
710 | #[cfg (test)] |
711 | mod tests { |
712 | #[cfg (feature = "clock" )] |
713 | use crate::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, Utc}; |
714 | |
715 | #[test ] |
716 | #[allow (deprecated)] |
717 | #[cfg (feature = "clock" )] |
718 | fn test_type_sizes() { |
719 | use core::mem::size_of; |
720 | assert_eq!(size_of::<NaiveDate>(), 4); |
721 | assert_eq!(size_of::<Option<NaiveDate>>(), 4); |
722 | assert_eq!(size_of::<NaiveTime>(), 8); |
723 | assert_eq!(size_of::<Option<NaiveTime>>(), 12); |
724 | assert_eq!(size_of::<NaiveDateTime>(), 12); |
725 | assert_eq!(size_of::<Option<NaiveDateTime>>(), 12); |
726 | |
727 | assert_eq!(size_of::<DateTime<Utc>>(), 12); |
728 | assert_eq!(size_of::<DateTime<FixedOffset>>(), 16); |
729 | assert_eq!(size_of::<DateTime<Local>>(), 16); |
730 | assert_eq!(size_of::<Option<DateTime<FixedOffset>>>(), 16); |
731 | } |
732 | } |
733 | |