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