Coverage Report

Created: 2025-11-16 06:34

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