chrono/
lib.rs

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