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