]> git.proxmox.com Git - rustc.git/blob - src/vendor/chrono/src/lib.rs
New upstream version 1.27.1+dfsg1
[rustc.git] / src / vendor / chrono / src / lib.rs
1 // This is a part of Chrono.
2 // See README.md and LICENSE.txt for details.
3
4 //! # Chrono 0.4.0
5 //!
6 //! Date and time handling for Rust.
7 //! It aims to be a feature-complete superset of
8 //! the [time](https://github.com/rust-lang-deprecated/time) library.
9 //! In particular,
10 //!
11 //! * Chrono strictly adheres to ISO 8601.
12 //! * Chrono is timezone-aware by default, with separate timezone-naive types.
13 //! * Chrono is space-optimal and (while not being the primary goal) reasonably efficient.
14 //!
15 //! There were several previous attempts to bring a good date and time library to Rust,
16 //! which Chrono builds upon and should acknowledge:
17 //!
18 //! * [Initial research on
19 //! the wiki](https://github.com/rust-lang/rust-wiki-backup/blob/master/Lib-datetime.md)
20 //! * Dietrich Epp's [datetime-rs](https://github.com/depp/datetime-rs)
21 //! * Luis de Bethencourt's [rust-datetime](https://github.com/luisbg/rust-datetime)
22 //!
23 //! Any significant changes to Chrono are documented in
24 //! the [`CHANGELOG.md`](https://github.com/chronotope/chrono/blob/master/CHANGELOG.md) file.
25 //!
26 //! ## Usage
27 //!
28 //! Put this in your `Cargo.toml`:
29 //!
30 //! ```toml
31 //! [dependencies]
32 //! chrono = "0.4"
33 //! ```
34 //!
35 //! Or, if you want [Serde](https://github.com/serde-rs/serde) or
36 //! [rustc-serialize](https://github.com/rust-lang-nursery/rustc-serialize) support,
37 //! include the features like this:
38 //!
39 //! ```toml
40 //! [dependencies]
41 //! chrono = { version = "0.4", features = ["serde", "rustc-serialize"] }
42 //! ```
43 //!
44 //! > Note that Chrono's support for rustc-serialize is now considered deprecated.
45 //! Starting from 0.4.0 there is no further guarantee that
46 //! the features available in Serde will be also available to rustc-serialize,
47 //! and the support can be removed in any future major version.
48 //! **Rustc-serialize users are strongly recommended to migrate to Serde.**
49 //!
50 //! Then put this in your crate root:
51 //!
52 //! ```rust
53 //! extern crate chrono;
54 //! ```
55 //!
56 //! Avoid using `use chrono::*;` as Chrono exports several modules other than types.
57 //! If you prefer the glob imports, use the following instead:
58 //!
59 //! ```rust
60 //! use chrono::prelude::*;
61 //! ```
62 //!
63 //! ## Overview
64 //!
65 //! ### Duration
66 //!
67 //! Chrono currently uses
68 //! the [`time::Duration`](https://doc.rust-lang.org/time/time/struct.Duration.html) type
69 //! from the `time` crate to represent the magnitude of a time span.
70 //! Since this has the same name to the newer, standard type for duration,
71 //! the reference will refer this type as `OldDuration`.
72 //! Note that this is an "accurate" duration represented as seconds and
73 //! nanoseconds and does not represent "nominal" components such as days or
74 //! months.
75 //!
76 //! Chrono does not yet natively support
77 //! the standard [`Duration`](https://doc.rust-lang.org/std/time/struct.Duration.html) type,
78 //! but it will be supported in the future.
79 //! Meanwhile you can convert between two types with
80 //! [`Duration::from_std`](https://doc.rust-lang.org/time/time/struct.Duration.html#method.from_std)
81 //! and
82 //! [`Duration::to_std`](https://doc.rust-lang.org/time/time/struct.Duration.html#method.to_std)
83 //! methods.
84 //!
85 //! ### Date and Time
86 //!
87 //! Chrono provides a
88 //! [**`DateTime`**](./struct.DateTime.html)
89 //! type to represent a date and a time in a timezone.
90 //!
91 //! For more abstract moment-in-time tracking such as internal timekeeping
92 //! that is unconcerned with timezones, consider
93 //! [`time::SystemTime`](https://doc.rust-lang.org/std/time/struct.SystemTime.html),
94 //! which tracks your system clock, or
95 //! [`time::Instant`](https://doc.rust-lang.org/std/time/struct.Instant.html), which
96 //! is an opaque but monotonically-increasing representation of a moment in time.
97 //!
98 //! `DateTime` is timezone-aware and must be constructed from
99 //! the [**`TimeZone`**](./offset/trait.TimeZone.html) object,
100 //! which defines how the local date is converted to and back from the UTC date.
101 //! There are three well-known `TimeZone` implementations:
102 //!
103 //! * [**`Utc`**](./offset/struct.Utc.html) specifies the UTC time zone. It is most efficient.
104 //!
105 //! * [**`Local`**](./offset/struct.Local.html) specifies the system local time zone.
106 //!
107 //! * [**`FixedOffset`**](./offset/struct.FixedOffset.html) specifies
108 //! an arbitrary, fixed time zone such as UTC+09:00 or UTC-10:30.
109 //! This often results from the parsed textual date and time.
110 //! Since it stores the most information and does not depend on the system environment,
111 //! you would want to normalize other `TimeZone`s into this type.
112 //!
113 //! `DateTime`s with different `TimeZone` types are distinct and do not mix,
114 //! but can be converted to each other using
115 //! the [`DateTime::with_timezone`](./struct.DateTime.html#method.with_timezone) method.
116 //!
117 //! You can get the current date and time in the UTC time zone
118 //! ([`Utc::now()`](./offset/struct.Utc.html#method.now))
119 //! or in the local time zone
120 //! ([`Local::now()`](./offset/struct.Local.html#method.now)).
121 //!
122 //! ```rust
123 //! use chrono::prelude::*;
124 //!
125 //! let utc: DateTime<Utc> = Utc::now(); // e.g. `2014-11-28T12:45:59.324310806Z`
126 //! let local: DateTime<Local> = Local::now(); // e.g. `2014-11-28T21:45:59.324310806+09:00`
127 //! # let _ = utc; let _ = local;
128 //! ```
129 //!
130 //! Alternatively, you can create your own date and time.
131 //! This is a bit verbose due to Rust's lack of function and method overloading,
132 //! but in turn we get a rich combination of initialization methods.
133 //!
134 //! ```rust
135 //! use chrono::prelude::*;
136 //! use chrono::offset::LocalResult;
137 //!
138 //! let dt = Utc.ymd(2014, 7, 8).and_hms(9, 10, 11); // `2014-07-08T09:10:11Z`
139 //! // July 8 is 188th day of the year 2014 (`o` for "ordinal")
140 //! assert_eq!(dt, Utc.yo(2014, 189).and_hms(9, 10, 11));
141 //! // July 8 is Tuesday in ISO week 28 of the year 2014.
142 //! assert_eq!(dt, Utc.isoywd(2014, 28, Weekday::Tue).and_hms(9, 10, 11));
143 //!
144 //! let dt = Utc.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12); // `2014-07-08T09:10:11.012Z`
145 //! assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_micro(9, 10, 11, 12_000));
146 //! assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_nano(9, 10, 11, 12_000_000));
147 //!
148 //! // dynamic verification
149 //! assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(21, 15, 33),
150 //! LocalResult::Single(Utc.ymd(2014, 7, 8).and_hms(21, 15, 33)));
151 //! assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(80, 15, 33), LocalResult::None);
152 //! assert_eq!(Utc.ymd_opt(2014, 7, 38).and_hms_opt(21, 15, 33), LocalResult::None);
153 //!
154 //! // other time zone objects can be used to construct a local datetime.
155 //! // obviously, `local_dt` is normally different from `dt`, but `fixed_dt` should be identical.
156 //! let local_dt = Local.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12);
157 //! let fixed_dt = FixedOffset::east(9 * 3600).ymd(2014, 7, 8).and_hms_milli(18, 10, 11, 12);
158 //! assert_eq!(dt, fixed_dt);
159 //! # let _ = local_dt;
160 //! ```
161 //!
162 //! Various properties are available to the date and time, and can be altered individually.
163 //! Most of them are defined in the traits [`Datelike`](./trait.Datelike.html) and
164 //! [`Timelike`](./trait.Timelike.html) which you should `use` before.
165 //! Addition and subtraction is also supported.
166 //! The following illustrates most supported operations to the date and time:
167 //!
168 //! ```rust
169 //! # extern crate chrono; extern crate time; fn main() {
170 //! use chrono::prelude::*;
171 //! use time::Duration;
172 //!
173 //! # /* we intentionally fake the datetime...
174 //! // assume this returned `2014-11-28T21:45:59.324310806+09:00`:
175 //! let dt = Local::now();
176 //! # */ // up to here. we now define a fixed datetime for the illustrative purpose.
177 //! # let dt = FixedOffset::east(9*3600).ymd(2014, 11, 28).and_hms_nano(21, 45, 59, 324310806);
178 //!
179 //! // property accessors
180 //! assert_eq!((dt.year(), dt.month(), dt.day()), (2014, 11, 28));
181 //! assert_eq!((dt.month0(), dt.day0()), (10, 27)); // for unfortunate souls
182 //! assert_eq!((dt.hour(), dt.minute(), dt.second()), (21, 45, 59));
183 //! assert_eq!(dt.weekday(), Weekday::Fri);
184 //! assert_eq!(dt.weekday().number_from_monday(), 5); // Mon=1, ..., Sat=7
185 //! assert_eq!(dt.ordinal(), 332); // the day of year
186 //! assert_eq!(dt.num_days_from_ce(), 735565); // the number of days from and including Jan 1, 1
187 //!
188 //! // time zone accessor and manipulation
189 //! assert_eq!(dt.offset().fix().local_minus_utc(), 9 * 3600);
190 //! assert_eq!(dt.timezone(), FixedOffset::east(9 * 3600));
191 //! assert_eq!(dt.with_timezone(&Utc), Utc.ymd(2014, 11, 28).and_hms_nano(12, 45, 59, 324310806));
192 //!
193 //! // a sample of property manipulations (validates dynamically)
194 //! assert_eq!(dt.with_day(29).unwrap().weekday(), Weekday::Sat); // 2014-11-29 is Saturday
195 //! assert_eq!(dt.with_day(32), None);
196 //! assert_eq!(dt.with_year(-300).unwrap().num_days_from_ce(), -109606); // November 29, 301 BCE
197 //!
198 //! // arithmetic operations
199 //! let dt1 = Utc.ymd(2014, 11, 14).and_hms(8, 9, 10);
200 //! let dt2 = Utc.ymd(2014, 11, 14).and_hms(10, 9, 8);
201 //! assert_eq!(dt1.signed_duration_since(dt2), Duration::seconds(-2 * 3600 + 2));
202 //! assert_eq!(dt2.signed_duration_since(dt1), Duration::seconds(2 * 3600 - 2));
203 //! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) + Duration::seconds(1_000_000_000),
204 //! Utc.ymd(2001, 9, 9).and_hms(1, 46, 40));
205 //! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) - Duration::seconds(1_000_000_000),
206 //! Utc.ymd(1938, 4, 24).and_hms(22, 13, 20));
207 //! # }
208 //! ```
209 //!
210 //! Formatting is done via the [`format`](./struct.DateTime.html#method.format) method,
211 //! which format is equivalent to the familiar `strftime` format.
212 //! (See the [`format::strftime` module documentation](./format/strftime/index.html#specifiers)
213 //! for full syntax.)
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 //! ```rust
221 //! use chrono::prelude::*;
222 //!
223 //! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
224 //! assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2014-11-28 12:00:09");
225 //! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), "Fri Nov 28 12:00:09 2014");
226 //! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), dt.format("%c").to_string());
227 //!
228 //! assert_eq!(dt.to_string(), "2014-11-28 12:00:09 UTC");
229 //! assert_eq!(dt.to_rfc2822(), "Fri, 28 Nov 2014 12:00:09 +0000");
230 //! assert_eq!(dt.to_rfc3339(), "2014-11-28T12:00:09+00:00");
231 //! assert_eq!(format!("{:?}", dt), "2014-11-28T12:00:09Z");
232 //! ```
233 //!
234 //! Parsing can be done with three methods:
235 //!
236 //! 1. The standard [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) trait
237 //! (and [`parse`](https://doc.rust-lang.org/std/primitive.str.html#method.parse) method
238 //! on a string) can be used for parsing `DateTime<FixedOffset>`, `DateTime<Utc>` and
239 //! `DateTime<Local>` values. This parses what the `{:?}`
240 //! ([`std::fmt::Debug`](https://doc.rust-lang.org/std/fmt/trait.Debug.html))
241 //! format specifier prints, and requires the offset to be present.
242 //!
243 //! 2. [`DateTime::parse_from_str`](./struct.DateTime.html#method.parse_from_str) parses
244 //! a date and time with offsets and returns `DateTime<FixedOffset>`.
245 //! This should be used when the offset is a part of input and the caller cannot guess that.
246 //! It *cannot* be used when the offset can be missing.
247 //! [`DateTime::parse_from_rfc2822`](./struct.DateTime.html#method.parse_from_rfc2822)
248 //! and
249 //! [`DateTime::parse_from_rfc3339`](./struct.DateTime.html#method.parse_from_rfc3339)
250 //! are similar but for well-known formats.
251 //!
252 //! 3. [`Offset::datetime_from_str`](./offset/trait.TimeZone.html#method.datetime_from_str) is
253 //! similar but returns `DateTime` of given offset.
254 //! When the explicit offset is missing from the input, it simply uses given offset.
255 //! It issues an error when the input contains an explicit offset different
256 //! from the current offset.
257 //!
258 //! More detailed control over the parsing process is available via
259 //! [`format`](./format/index.html) module.
260 //!
261 //! ```rust
262 //! use chrono::prelude::*;
263 //!
264 //! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
265 //! let fixed_dt = dt.with_timezone(&FixedOffset::east(9*3600));
266 //!
267 //! // method 1
268 //! assert_eq!("2014-11-28T12:00:09Z".parse::<DateTime<Utc>>(), Ok(dt.clone()));
269 //! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<Utc>>(), Ok(dt.clone()));
270 //! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<FixedOffset>>(), Ok(fixed_dt.clone()));
271 //!
272 //! // method 2
273 //! assert_eq!(DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z"),
274 //! Ok(fixed_dt.clone()));
275 //! assert_eq!(DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900"),
276 //! Ok(fixed_dt.clone()));
277 //! assert_eq!(DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00"), Ok(fixed_dt.clone()));
278 //!
279 //! // method 3
280 //! assert_eq!(Utc.datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S"), Ok(dt.clone()));
281 //! assert_eq!(Utc.datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y"), Ok(dt.clone()));
282 //!
283 //! // oops, the year is missing!
284 //! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T %Y").is_err());
285 //! // oops, the format string does not include the year at all!
286 //! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T").is_err());
287 //! // oops, the weekday is incorrect!
288 //! assert!(Utc.datetime_from_str("Sat Nov 28 12:00:09 2014", "%a %b %e %T %Y").is_err());
289 //! ```
290 //!
291 //! ### Conversion from and to EPOCH timestamps
292 //!
293 //! Use [`Utc.timestamp(seconds, nanoseconds)`](./offset/trait.TimeZone.html#method.timestamp)
294 //! to construct a [`DateTime<Utc>`](./struct.DateTime.html) from a UNIX timestamp
295 //! (seconds, nanoseconds that passed since January 1st 1970).
296 //!
297 //! Use [`DateTime.timestamp`](./struct.DateTime.html#method.timestamp) to get the timestamp (in seconds)
298 //! from a [`DateTime`](./struct.DateTime.html). Additionally, you can use
299 //! [`DateTime.timestamp_subsec_nanos`](./struct.DateTime.html#method.timestamp_subsec_nanos)
300 //! to get the number of additional number of nanoseconds.
301 //!
302 //! ```rust
303 //! # use chrono::DateTime;
304 //! # use chrono::Utc;
305 //! // We need the trait in scope to use Utc::timestamp().
306 //! use chrono::TimeZone;
307 //!
308 //! // Construct a datetime from epoch:
309 //! let dt = Utc.timestamp(1_500_000_000, 0);
310 //! assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000");
311 //!
312 //! // Get epoch value from a datetime:
313 //! let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap();
314 //! assert_eq!(dt.timestamp(), 1_500_000_000);
315 //! ```
316 //!
317 //! ### Individual date
318 //!
319 //! Chrono also provides an individual date type ([**`Date`**](./struct.Date.html)).
320 //! It also has time zones attached, and have to be constructed via time zones.
321 //! Most operations available to `DateTime` are also available to `Date` whenever appropriate.
322 //!
323 //! ```rust
324 //! use chrono::prelude::*;
325 //! use chrono::offset::LocalResult;
326 //!
327 //! # // these *may* fail, but only very rarely. just rerun the test if you were that unfortunate ;)
328 //! assert_eq!(Utc::today(), Utc::now().date());
329 //! assert_eq!(Local::today(), Local::now().date());
330 //!
331 //! assert_eq!(Utc.ymd(2014, 11, 28).weekday(), Weekday::Fri);
332 //! assert_eq!(Utc.ymd_opt(2014, 11, 31), LocalResult::None);
333 //! assert_eq!(Utc.ymd(2014, 11, 28).and_hms_milli(7, 8, 9, 10).format("%H%M%S").to_string(),
334 //! "070809");
335 //! ```
336 //!
337 //! There is no timezone-aware `Time` due to the lack of usefulness and also the complexity.
338 //!
339 //! `DateTime` has [`date`](./struct.DateTime.html#method.date) method
340 //! which returns a `Date` which represents its date component.
341 //! There is also a [`time`](./struct.DateTime.html#method.time) method,
342 //! which simply returns a naive local time described below.
343 //!
344 //! ### Naive date and time
345 //!
346 //! Chrono provides naive counterparts to `Date`, (non-existent) `Time` and `DateTime`
347 //! as [**`NaiveDate`**](./naive/struct.NaiveDate.html),
348 //! [**`NaiveTime`**](./naive/struct.NaiveTime.html) and
349 //! [**`NaiveDateTime`**](./naive/struct.NaiveDateTime.html) respectively.
350 //!
351 //! They have almost equivalent interfaces as their timezone-aware twins,
352 //! but are not associated to time zones obviously and can be quite low-level.
353 //! They are mostly useful for building blocks for higher-level types.
354 //!
355 //! Timezone-aware `DateTime` and `Date` types have two methods returning naive versions:
356 //! [`naive_local`](./struct.DateTime.html#method.naive_local) returns
357 //! a view to the naive local time,
358 //! and [`naive_utc`](./struct.DateTime.html#method.naive_utc) returns
359 //! a view to the naive UTC time.
360 //!
361 //! ## Limitations
362 //!
363 //! Only proleptic Gregorian calendar (i.e. extended to support older dates) is supported.
364 //! Be very careful if you really have to deal with pre-20C dates, they can be in Julian or others.
365 //!
366 //! Date types are limited in about +/- 262,000 years from the common epoch.
367 //! Time types are limited in the nanosecond accuracy.
368 //!
369 //! [Leap seconds are supported in the representation but
370 //! Chrono doesn't try to make use of them](./naive/struct.NaiveTime.html#leap-second-handling).
371 //! (The main reason is that leap seconds are not really predictable.)
372 //! Almost *every* operation over the possible leap seconds will ignore them.
373 //! Consider using `NaiveDateTime` with the implicit TAI (International Atomic Time) scale
374 //! if you want.
375 //!
376 //! Chrono inherently does not support an inaccurate or partial date and time representation.
377 //! Any operation that can be ambiguous will return `None` in such cases.
378 //! For example, "a month later" of 2014-01-30 is not well-defined
379 //! and consequently `Utc.ymd(2014, 1, 30).with_month(2)` returns `None`.
380 //!
381 //! Advanced time zone handling is not yet supported.
382 //! For now you can try the [Chrono-tz](https://github.com/chronotope/chrono-tz/) crate instead.
383
384 #![doc(html_root_url = "https://docs.rs/chrono/0.4.0/")]
385
386 #![cfg_attr(bench, feature(test))] // lib stability features as per RFC #507
387 #![deny(missing_docs)]
388 #![deny(missing_debug_implementations)]
389
390 // The explicit 'static lifetimes are still needed for rustc 1.13-16
391 // backward compatibility, and this appeases clippy. If minimum rustc
392 // becomes 1.17, should be able to remove this, those 'static lifetimes,
393 // and use `static` in a lot of places `const` is used now.
394 //
395 // Similarly, redundant_field_names lints on not using the
396 // field-init-shorthand, which was stabilized in rust 1.17.
397 #![cfg_attr(feature = "cargo-clippy", allow(const_static_lifetime, redundant_field_names))]
398
399 extern crate time as oldtime;
400 extern crate num_integer;
401 extern crate num_traits;
402 #[cfg(feature = "rustc-serialize")]
403 extern crate rustc_serialize;
404 #[cfg(feature = "serde")]
405 extern crate serde as serdelib;
406
407 // this reexport is to aid the transition and should not be in the prelude!
408 pub use oldtime::Duration;
409
410 #[doc(no_inline)] pub use offset::{TimeZone, Offset, LocalResult, Utc, FixedOffset, Local};
411 #[doc(no_inline)] pub use naive::{NaiveDate, IsoWeek, NaiveTime, NaiveDateTime};
412 pub use date::{Date, MIN_DATE, MAX_DATE};
413 pub use datetime::{DateTime, SecondsFormat};
414 #[cfg(feature = "rustc-serialize")] pub use datetime::rustc_serialize::TsSeconds;
415 pub use format::{ParseError, ParseResult};
416 pub use round::SubsecRound;
417
418 /// A convenience module appropriate for glob imports (`use chrono::prelude::*;`).
419 pub mod prelude {
420 #[doc(no_inline)] pub use {Datelike, Timelike, Weekday};
421 #[doc(no_inline)] pub use {TimeZone, Offset};
422 #[doc(no_inline)] pub use {Utc, FixedOffset, Local};
423 #[doc(no_inline)] pub use {NaiveDate, NaiveTime, NaiveDateTime};
424 #[doc(no_inline)] pub use Date;
425 #[doc(no_inline)] pub use {DateTime, SecondsFormat};
426 #[doc(no_inline)] pub use SubsecRound;
427 }
428
429 // useful throughout the codebase
430 macro_rules! try_opt {
431 ($e:expr) => (match $e { Some(v) => v, None => return None })
432 }
433
434 mod div;
435 pub mod offset;
436 pub mod naive {
437 //! Date and time types which do not concern about the timezones.
438 //!
439 //! They are primarily building blocks for other types
440 //! (e.g. [`TimeZone`](../offset/trait.TimeZone.html)),
441 //! but can be also used for the simpler date and time handling.
442
443 mod internals;
444 mod date;
445 mod isoweek;
446 mod time;
447 mod datetime;
448
449 pub use self::date::{NaiveDate, MIN_DATE, MAX_DATE};
450 pub use self::isoweek::IsoWeek;
451 pub use self::time::NaiveTime;
452 pub use self::datetime::NaiveDateTime;
453 #[cfg(feature = "rustc-serialize")]
454 pub use self::datetime::rustc_serialize::TsSeconds;
455
456
457 /// Serialization/Deserialization of naive types in alternate formats
458 ///
459 /// The various modules in here are intended to be used with serde's [`with`
460 /// annotation][1] to serialize as something other than the default [RFC
461 /// 3339][2] format.
462 ///
463 /// [1]: https://serde.rs/attributes.html#field-attributes
464 /// [2]: https://tools.ietf.org/html/rfc3339
465 #[cfg(feature = "serde")]
466 pub mod serde {
467 pub use super::datetime::serde::*;
468 }
469 }
470 mod date;
471 mod datetime;
472 pub mod format;
473 mod round;
474
475 /// Serialization/Deserialization in alternate formats
476 ///
477 /// The various modules in here are intended to be used with serde's [`with`
478 /// annotation][1] to serialize as something other than the default [RFC
479 /// 3339][2] format.
480 ///
481 /// [1]: https://serde.rs/attributes.html#field-attributes
482 /// [2]: https://tools.ietf.org/html/rfc3339
483 #[cfg(feature = "serde")]
484 pub mod serde {
485 pub use super::datetime::serde::*;
486 }
487
488 /// The day of week.
489 ///
490 /// The order of the days of week depends on the context.
491 /// (This is why this type does *not* implement `PartialOrd` or `Ord` traits.)
492 /// One should prefer `*_from_monday` or `*_from_sunday` methods to get the correct result.
493 #[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
494 #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
495 pub enum Weekday {
496 /// Monday.
497 Mon = 0,
498 /// Tuesday.
499 Tue = 1,
500 /// Wednesday.
501 Wed = 2,
502 /// Thursday.
503 Thu = 3,
504 /// Friday.
505 Fri = 4,
506 /// Saturday.
507 Sat = 5,
508 /// Sunday.
509 Sun = 6,
510 }
511
512 impl Weekday {
513 /// The next day in the week.
514 ///
515 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
516 /// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
517 /// `w.succ()`: | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun` | `Mon`
518 #[inline]
519 pub fn succ(&self) -> Weekday {
520 match *self {
521 Weekday::Mon => Weekday::Tue,
522 Weekday::Tue => Weekday::Wed,
523 Weekday::Wed => Weekday::Thu,
524 Weekday::Thu => Weekday::Fri,
525 Weekday::Fri => Weekday::Sat,
526 Weekday::Sat => Weekday::Sun,
527 Weekday::Sun => Weekday::Mon,
528 }
529 }
530
531 /// The previous day in the week.
532 ///
533 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
534 /// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
535 /// `w.pred()`: | `Sun` | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat`
536 #[inline]
537 pub fn pred(&self) -> Weekday {
538 match *self {
539 Weekday::Mon => Weekday::Sun,
540 Weekday::Tue => Weekday::Mon,
541 Weekday::Wed => Weekday::Tue,
542 Weekday::Thu => Weekday::Wed,
543 Weekday::Fri => Weekday::Thu,
544 Weekday::Sat => Weekday::Fri,
545 Weekday::Sun => Weekday::Sat,
546 }
547 }
548
549 /// Returns a day-of-week number starting from Monday = 1. (ISO 8601 weekday number)
550 ///
551 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
552 /// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
553 /// `w.number_from_monday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 7
554 #[inline]
555 pub fn number_from_monday(&self) -> u32 {
556 match *self {
557 Weekday::Mon => 1,
558 Weekday::Tue => 2,
559 Weekday::Wed => 3,
560 Weekday::Thu => 4,
561 Weekday::Fri => 5,
562 Weekday::Sat => 6,
563 Weekday::Sun => 7,
564 }
565 }
566
567 /// Returns a day-of-week number starting from Sunday = 1.
568 ///
569 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
570 /// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
571 /// `w.number_from_sunday()`: | 2 | 3 | 4 | 5 | 6 | 7 | 1
572 #[inline]
573 pub fn number_from_sunday(&self) -> u32 {
574 match *self {
575 Weekday::Mon => 2,
576 Weekday::Tue => 3,
577 Weekday::Wed => 4,
578 Weekday::Thu => 5,
579 Weekday::Fri => 6,
580 Weekday::Sat => 7,
581 Weekday::Sun => 1,
582 }
583 }
584
585 /// Returns a day-of-week number starting from Monday = 0.
586 ///
587 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
588 /// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
589 /// `w.num_days_from_monday()`: | 0 | 1 | 2 | 3 | 4 | 5 | 6
590 #[inline]
591 pub fn num_days_from_monday(&self) -> u32 {
592 match *self {
593 Weekday::Mon => 0,
594 Weekday::Tue => 1,
595 Weekday::Wed => 2,
596 Weekday::Thu => 3,
597 Weekday::Fri => 4,
598 Weekday::Sat => 5,
599 Weekday::Sun => 6,
600 }
601 }
602
603 /// Returns a day-of-week number starting from Sunday = 0.
604 ///
605 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
606 /// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
607 /// `w.num_days_from_sunday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 0
608 #[inline]
609 pub fn num_days_from_sunday(&self) -> u32 {
610 match *self {
611 Weekday::Mon => 1,
612 Weekday::Tue => 2,
613 Weekday::Wed => 3,
614 Weekday::Thu => 4,
615 Weekday::Fri => 5,
616 Weekday::Sat => 6,
617 Weekday::Sun => 0,
618 }
619 }
620 }
621
622 /// Any weekday can be represented as an integer from 0 to 6, which equals to
623 /// [`Weekday::num_days_from_monday`](#method.num_days_from_monday) in this implementation.
624 /// Do not heavily depend on this though; use explicit methods whenever possible.
625 impl num_traits::FromPrimitive for Weekday {
626 #[inline]
627 fn from_i64(n: i64) -> Option<Weekday> {
628 match n {
629 0 => Some(Weekday::Mon),
630 1 => Some(Weekday::Tue),
631 2 => Some(Weekday::Wed),
632 3 => Some(Weekday::Thu),
633 4 => Some(Weekday::Fri),
634 5 => Some(Weekday::Sat),
635 6 => Some(Weekday::Sun),
636 _ => None,
637 }
638 }
639
640 #[inline]
641 fn from_u64(n: u64) -> Option<Weekday> {
642 match n {
643 0 => Some(Weekday::Mon),
644 1 => Some(Weekday::Tue),
645 2 => Some(Weekday::Wed),
646 3 => Some(Weekday::Thu),
647 4 => Some(Weekday::Fri),
648 5 => Some(Weekday::Sat),
649 6 => Some(Weekday::Sun),
650 _ => None,
651 }
652 }
653 }
654
655 use std::fmt;
656
657 /// An error resulting from reading `Weekday` value with `FromStr`.
658 #[derive(Clone, PartialEq)]
659 pub struct ParseWeekdayError {
660 _dummy: (),
661 }
662
663 impl fmt::Debug for ParseWeekdayError {
664 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
665 write!(f, "ParseWeekdayError {{ .. }}")
666 }
667 }
668
669 // the actual `FromStr` implementation is in the `format` module to leverage the existing code
670
671 #[cfg(feature = "serde")]
672 mod weekday_serde {
673 use super::Weekday;
674 use std::fmt;
675 use serdelib::{ser, de};
676
677 impl ser::Serialize for Weekday {
678 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
679 where S: ser::Serializer
680 {
681 serializer.serialize_str(&format!("{:?}", self))
682 }
683 }
684
685 struct WeekdayVisitor;
686
687 impl<'de> de::Visitor<'de> for WeekdayVisitor {
688 type Value = Weekday;
689
690 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
691 write!(f, "Weekday")
692 }
693
694 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
695 where E: de::Error
696 {
697 value.parse().map_err(|_| E::custom("short or long weekday names expected"))
698 }
699 }
700
701 impl<'de> de::Deserialize<'de> for Weekday {
702 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
703 where D: de::Deserializer<'de>
704 {
705 deserializer.deserialize_str(WeekdayVisitor)
706 }
707 }
708
709 #[cfg(test)]
710 extern crate serde_json;
711
712 #[test]
713 fn test_serde_serialize() {
714 use self::serde_json::to_string;
715 use Weekday::*;
716
717 let cases: Vec<(Weekday, &str)> = vec![
718 (Mon, "\"Mon\""),
719 (Tue, "\"Tue\""),
720 (Wed, "\"Wed\""),
721 (Thu, "\"Thu\""),
722 (Fri, "\"Fri\""),
723 (Sat, "\"Sat\""),
724 (Sun, "\"Sun\""),
725 ];
726
727 for (weekday, expected_str) in cases {
728 let string = to_string(&weekday).unwrap();
729 assert_eq!(string, expected_str);
730 }
731 }
732
733 #[test]
734 fn test_serde_deserialize() {
735 use self::serde_json::from_str;
736 use Weekday::*;
737
738 let cases: Vec<(&str, Weekday)> = vec![
739 ("\"mon\"", Mon),
740 ("\"MONDAY\"", Mon),
741 ("\"MonDay\"", Mon),
742 ("\"mOn\"", Mon),
743 ("\"tue\"", Tue),
744 ("\"tuesday\"", Tue),
745 ("\"wed\"", Wed),
746 ("\"wednesday\"", Wed),
747 ("\"thu\"", Thu),
748 ("\"thursday\"", Thu),
749 ("\"fri\"", Fri),
750 ("\"friday\"", Fri),
751 ("\"sat\"", Sat),
752 ("\"saturday\"", Sat),
753 ("\"sun\"", Sun),
754 ("\"sunday\"", Sun),
755 ];
756
757 for (str, expected_weekday) in cases {
758 let weekday = from_str::<Weekday>(str).unwrap();
759 assert_eq!(weekday, expected_weekday);
760 }
761
762 let errors: Vec<&str> = vec![
763 "\"not a weekday\"",
764 "\"monDAYs\"",
765 "\"mond\"",
766 "mon",
767 "\"thur\"",
768 "\"thurs\"",
769 ];
770
771 for str in errors {
772 from_str::<Weekday>(str).unwrap_err();
773 }
774 }
775 }
776
777 /// The common set of methods for date component.
778 pub trait Datelike: Sized {
779 /// Returns the year number in the [calendar date](./naive/struct.NaiveDate.html#calendar-date).
780 fn year(&self) -> i32;
781
782 /// Returns the absolute year number starting from 1 with a boolean flag,
783 /// which is false when the year predates the epoch (BCE/BC) and true otherwise (CE/AD).
784 #[inline]
785 fn year_ce(&self) -> (bool, u32) {
786 let year = self.year();
787 if year < 1 {
788 (false, (1 - year) as u32)
789 } else {
790 (true, year as u32)
791 }
792 }
793
794 /// Returns the month number starting from 1.
795 ///
796 /// The return value ranges from 1 to 12.
797 fn month(&self) -> u32;
798
799 /// Returns the month number starting from 0.
800 ///
801 /// The return value ranges from 0 to 11.
802 fn month0(&self) -> u32;
803
804 /// Returns the day of month starting from 1.
805 ///
806 /// The return value ranges from 1 to 31. (The last day of month differs by months.)
807 fn day(&self) -> u32;
808
809 /// Returns the day of month starting from 0.
810 ///
811 /// The return value ranges from 0 to 30. (The last day of month differs by months.)
812 fn day0(&self) -> u32;
813
814 /// Returns the day of year starting from 1.
815 ///
816 /// The return value ranges from 1 to 366. (The last day of year differs by years.)
817 fn ordinal(&self) -> u32;
818
819 /// Returns the day of year starting from 0.
820 ///
821 /// The return value ranges from 0 to 365. (The last day of year differs by years.)
822 fn ordinal0(&self) -> u32;
823
824 /// Returns the day of week.
825 fn weekday(&self) -> Weekday;
826
827 /// Returns the ISO week.
828 fn iso_week(&self) -> IsoWeek;
829
830 /// Makes a new value with the year number changed.
831 ///
832 /// Returns `None` when the resulting value would be invalid.
833 fn with_year(&self, year: i32) -> Option<Self>;
834
835 /// Makes a new value with the month number (starting from 1) changed.
836 ///
837 /// Returns `None` when the resulting value would be invalid.
838 fn with_month(&self, month: u32) -> Option<Self>;
839
840 /// Makes a new value with the month number (starting from 0) changed.
841 ///
842 /// Returns `None` when the resulting value would be invalid.
843 fn with_month0(&self, month0: u32) -> Option<Self>;
844
845 /// Makes a new value with the day of month (starting from 1) changed.
846 ///
847 /// Returns `None` when the resulting value would be invalid.
848 fn with_day(&self, day: u32) -> Option<Self>;
849
850 /// Makes a new value with the day of month (starting from 0) changed.
851 ///
852 /// Returns `None` when the resulting value would be invalid.
853 fn with_day0(&self, day0: u32) -> Option<Self>;
854
855 /// Makes a new value with the day of year (starting from 1) changed.
856 ///
857 /// Returns `None` when the resulting value would be invalid.
858 fn with_ordinal(&self, ordinal: u32) -> Option<Self>;
859
860 /// Makes a new value with the day of year (starting from 0) changed.
861 ///
862 /// Returns `None` when the resulting value would be invalid.
863 fn with_ordinal0(&self, ordinal0: u32) -> Option<Self>;
864
865 /// Returns the number of days since January 1, 1 (Day 1) in the proleptic Gregorian calendar.
866 fn num_days_from_ce(&self) -> i32 {
867 // we know this wouldn't overflow since year is limited to 1/2^13 of i32's full range.
868 let mut year = self.year() - 1;
869 let mut ndays = 0;
870 if year < 0 {
871 let excess = 1 + (-year) / 400;
872 year += excess * 400;
873 ndays -= excess * 146_097;
874 }
875 let div_100 = year / 100;
876 ndays += ((year * 1461) >> 2) - div_100 + (div_100 >> 2);
877 ndays + self.ordinal() as i32
878 }
879 }
880
881 /// The common set of methods for time component.
882 pub trait Timelike: Sized {
883 /// Returns the hour number from 0 to 23.
884 fn hour(&self) -> u32;
885
886 /// Returns the hour number from 1 to 12 with a boolean flag,
887 /// which is false for AM and true for PM.
888 #[inline]
889 fn hour12(&self) -> (bool, u32) {
890 let hour = self.hour();
891 let mut hour12 = hour % 12;
892 if hour12 == 0 {
893 hour12 = 12;
894 }
895 (hour >= 12, hour12)
896 }
897
898 /// Returns the minute number from 0 to 59.
899 fn minute(&self) -> u32;
900
901 /// Returns the second number from 0 to 59.
902 fn second(&self) -> u32;
903
904 /// Returns the number of nanoseconds since the whole non-leap second.
905 /// The range from 1,000,000,000 to 1,999,999,999 represents
906 /// the [leap second](./naive/struct.NaiveTime.html#leap-second-handling).
907 fn nanosecond(&self) -> u32;
908
909 /// Makes a new value with the hour number changed.
910 ///
911 /// Returns `None` when the resulting value would be invalid.
912 fn with_hour(&self, hour: u32) -> Option<Self>;
913
914 /// Makes a new value with the minute number changed.
915 ///
916 /// Returns `None` when the resulting value would be invalid.
917 fn with_minute(&self, min: u32) -> Option<Self>;
918
919 /// Makes a new value with the second number changed.
920 ///
921 /// Returns `None` when the resulting value would be invalid.
922 /// As with the [`second`](#tymethod.second) method,
923 /// the input range is restricted to 0 through 59.
924 fn with_second(&self, sec: u32) -> Option<Self>;
925
926 /// Makes a new value with nanoseconds since the whole non-leap second changed.
927 ///
928 /// Returns `None` when the resulting value would be invalid.
929 /// As with the [`nanosecond`](#tymethod.nanosecond) method,
930 /// the input range can exceed 1,000,000,000 for leap seconds.
931 fn with_nanosecond(&self, nano: u32) -> Option<Self>;
932
933 /// Returns the number of non-leap seconds past the last midnight.
934 #[inline]
935 fn num_seconds_from_midnight(&self) -> u32 {
936 self.hour() * 3600 + self.minute() * 60 + self.second()
937 }
938 }
939
940 #[cfg(test)] extern crate num_iter;
941
942 #[test]
943 fn test_readme_doomsday() {
944 use num_iter::range_inclusive;
945
946 for y in range_inclusive(naive::MIN_DATE.year(), naive::MAX_DATE.year()) {
947 // even months
948 let d4 = NaiveDate::from_ymd(y, 4, 4);
949 let d6 = NaiveDate::from_ymd(y, 6, 6);
950 let d8 = NaiveDate::from_ymd(y, 8, 8);
951 let d10 = NaiveDate::from_ymd(y, 10, 10);
952 let d12 = NaiveDate::from_ymd(y, 12, 12);
953
954 // nine to five, seven-eleven
955 let d59 = NaiveDate::from_ymd(y, 5, 9);
956 let d95 = NaiveDate::from_ymd(y, 9, 5);
957 let d711 = NaiveDate::from_ymd(y, 7, 11);
958 let d117 = NaiveDate::from_ymd(y, 11, 7);
959
960 // "March 0"
961 let d30 = NaiveDate::from_ymd(y, 3, 1).pred();
962
963 let weekday = d30.weekday();
964 let other_dates = [d4, d6, d8, d10, d12, d59, d95, d711, d117];
965 assert!(other_dates.iter().all(|d| d.weekday() == weekday));
966 }
967 }