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