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