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://docs.rs/time/0.1.40/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; extern crate time; fn main() {
162 //! use chrono::prelude::*;
163 //! use time::Duration;
164 //!
165 //! # /* we intentionally fake the datetime...
166 //! // assume this returned `2014-11-28T21:45:59.324310806+09:00`:
167 //! let dt = Local::now();
168 //! # */ // up to here. we now define a fixed datetime for the illustrative purpose.
169 //! # let dt = FixedOffset::east(9*3600).ymd(2014, 11, 28).and_hms_nano(21, 45, 59, 324310806);
170 //!
171 //! // property accessors
172 //! assert_eq!((dt.year(), dt.month(), dt.day()), (2014, 11, 28));
173 //! assert_eq!((dt.month0(), dt.day0()), (10, 27)); // for unfortunate souls
174 //! assert_eq!((dt.hour(), dt.minute(), dt.second()), (21, 45, 59));
175 //! assert_eq!(dt.weekday(), Weekday::Fri);
176 //! assert_eq!(dt.weekday().number_from_monday(), 5); // Mon=1, ..., Sat=7
177 //! assert_eq!(dt.ordinal(), 332); // the day of year
178 //! assert_eq!(dt.num_days_from_ce(), 735565); // the number of days from and including Jan 1, 1
179 //!
180 //! // time zone accessor and manipulation
181 //! assert_eq!(dt.offset().fix().local_minus_utc(), 9 * 3600);
182 //! assert_eq!(dt.timezone(), FixedOffset::east(9 * 3600));
183 //! assert_eq!(dt.with_timezone(&Utc), Utc.ymd(2014, 11, 28).and_hms_nano(12, 45, 59, 324310806));
184 //!
185 //! // a sample of property manipulations (validates dynamically)
186 //! assert_eq!(dt.with_day(29).unwrap().weekday(), Weekday::Sat); // 2014-11-29 is Saturday
187 //! assert_eq!(dt.with_day(32), None);
188 //! assert_eq!(dt.with_year(-300).unwrap().num_days_from_ce(), -109606); // November 29, 301 BCE
189 //!
190 //! // arithmetic operations
191 //! let dt1 = Utc.ymd(2014, 11, 14).and_hms(8, 9, 10);
192 //! let dt2 = Utc.ymd(2014, 11, 14).and_hms(10, 9, 8);
193 //! assert_eq!(dt1.signed_duration_since(dt2), Duration::seconds(-2 * 3600 + 2));
194 //! assert_eq!(dt2.signed_duration_since(dt1), Duration::seconds(2 * 3600 - 2));
195 //! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) + Duration::seconds(1_000_000_000),
196 //! Utc.ymd(2001, 9, 9).and_hms(1, 46, 40));
197 //! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) - Duration::seconds(1_000_000_000),
198 //! Utc.ymd(1938, 4, 24).and_hms(22, 13, 20));
199 //! # }
200 //! ```
201 //!
202 //! ### Formatting and Parsing
203 //!
204 //! Formatting is done via the [`format`](./struct.DateTime.html#method.format) method,
205 //! which format is equivalent to the familiar `strftime` format.
206 //!
207 //! See [`format::strftime`](./format/strftime/index.html#specifiers)
208 //! documentation for full syntax and list of specifiers.
209 //!
210 //! The default `to_string` method and `{:?}` specifier also give a reasonable representation.
211 //! Chrono also provides [`to_rfc2822`](./struct.DateTime.html#method.to_rfc2822) and
212 //! [`to_rfc3339`](./struct.DateTime.html#method.to_rfc3339) methods
213 //! for well-known formats.
214 //!
215 //! ```rust
216 //! use chrono::prelude::*;
217 //!
218 //! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
219 //! assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2014-11-28 12:00:09");
220 //! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), "Fri Nov 28 12:00:09 2014");
221 //! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), dt.format("%c").to_string());
222 //!
223 //! assert_eq!(dt.to_string(), "2014-11-28 12:00:09 UTC");
224 //! assert_eq!(dt.to_rfc2822(), "Fri, 28 Nov 2014 12:00:09 +0000");
225 //! assert_eq!(dt.to_rfc3339(), "2014-11-28T12:00:09+00:00");
226 //! assert_eq!(format!("{:?}", dt), "2014-11-28T12:00:09Z");
227 //!
228 //! // Note that milli/nanoseconds are only printed if they are non-zero
229 //! let dt_nano = Utc.ymd(2014, 11, 28).and_hms_nano(12, 0, 9, 1);
230 //! assert_eq!(format!("{:?}", dt_nano), "2014-11-28T12:00:09.000000001Z");
231 //! ```
232 //!
233 //! Parsing can be done with three methods:
234 //!
235 //! 1. The standard [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) trait
236 //! (and [`parse`](https://doc.rust-lang.org/std/primitive.str.html#method.parse) method
237 //! on a string) can be used for parsing `DateTime<FixedOffset>`, `DateTime<Utc>` and
238 //! `DateTime<Local>` values. This parses what the `{:?}`
239 //! ([`std::fmt::Debug`](https://doc.rust-lang.org/std/fmt/trait.Debug.html))
240 //! format specifier prints, and requires the offset to be present.
241 //!
242 //! 2. [`DateTime::parse_from_str`](./struct.DateTime.html#method.parse_from_str) parses
243 //! a date and time with offsets and returns `DateTime<FixedOffset>`.
244 //! This should be used when the offset is a part of input and the caller cannot guess that.
245 //! It *cannot* be used when the offset can be missing.
246 //! [`DateTime::parse_from_rfc2822`](./struct.DateTime.html#method.parse_from_rfc2822)
247 //! and
248 //! [`DateTime::parse_from_rfc3339`](./struct.DateTime.html#method.parse_from_rfc3339)
249 //! are similar but for well-known formats.
250 //!
251 //! 3. [`Offset::datetime_from_str`](./offset/trait.TimeZone.html#method.datetime_from_str) is
252 //! similar but returns `DateTime` of given offset.
253 //! When the explicit offset is missing from the input, it simply uses given offset.
254 //! It issues an error when the input contains an explicit offset different
255 //! from the current offset.
256 //!
257 //! More detailed control over the parsing process is available via
258 //! [`format`](./format/index.html) module.
259 //!
260 //! ```rust
261 //! use chrono::prelude::*;
262 //!
263 //! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
264 //! let fixed_dt = dt.with_timezone(&FixedOffset::east(9*3600));
265 //!
266 //! // method 1
267 //! assert_eq!("2014-11-28T12:00:09Z".parse::<DateTime<Utc>>(), Ok(dt.clone()));
268 //! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<Utc>>(), Ok(dt.clone()));
269 //! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<FixedOffset>>(), Ok(fixed_dt.clone()));
270 //!
271 //! // method 2
272 //! assert_eq!(DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z"),
273 //! Ok(fixed_dt.clone()));
274 //! assert_eq!(DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900"),
275 //! Ok(fixed_dt.clone()));
276 //! assert_eq!(DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00"), Ok(fixed_dt.clone()));
277 //!
278 //! // method 3
279 //! assert_eq!(Utc.datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S"), Ok(dt.clone()));
280 //! assert_eq!(Utc.datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y"), Ok(dt.clone()));
281 //!
282 //! // oops, the year is missing!
283 //! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T %Y").is_err());
284 //! // oops, the format string does not include the year at all!
285 //! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T").is_err());
286 //! // oops, the weekday is incorrect!
287 //! assert!(Utc.datetime_from_str("Sat Nov 28 12:00:09 2014", "%a %b %e %T %Y").is_err());
288 //! ```
289 //!
290 //! Again : See [`format::strftime`](./format/strftime/index.html#specifiers)
291 //! documentation for full syntax and list of specifiers.
292 //!
293 //! ### Conversion from and to EPOCH timestamps
294 //!
295 //! Use [`Utc.timestamp(seconds, nanoseconds)`](./offset/trait.TimeZone.html#method.timestamp)
296 //! to construct a [`DateTime<Utc>`](./struct.DateTime.html) from a UNIX timestamp
297 //! (seconds, nanoseconds that passed since January 1st 1970).
298 //!
299 //! Use [`DateTime.timestamp`](./struct.DateTime.html#method.timestamp) to get the timestamp (in seconds)
300 //! from a [`DateTime`](./struct.DateTime.html). Additionally, you can use
301 //! [`DateTime.timestamp_subsec_nanos`](./struct.DateTime.html#method.timestamp_subsec_nanos)
302 //! to get the number of additional number of nanoseconds.
303 //!
304 //! ```rust
305 //! # use chrono::DateTime;
306 //! # use chrono::Utc;
307 //! // We need the trait in scope to use Utc::timestamp().
308 //! use chrono::TimeZone;
309 //!
310 //! // Construct a datetime from epoch:
311 //! let dt = Utc.timestamp(1_500_000_000, 0);
312 //! assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000");
313 //!
314 //! // Get epoch value from a datetime:
315 //! let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap();
316 //! assert_eq!(dt.timestamp(), 1_500_000_000);
317 //! ```
318 //!
319 //! ### Individual date
320 //!
321 //! Chrono also provides an individual date type ([**`Date`**](./struct.Date.html)).
322 //! It also has time zones attached, and have to be constructed via time zones.
323 //! Most operations available to `DateTime` are also available to `Date` whenever appropriate.
324 //!
325 //! ```rust
326 //! use chrono::prelude::*;
327 //! use chrono::offset::LocalResult;
328 //!
329 //! # // these *may* fail, but only very rarely. just rerun the test if you were that unfortunate ;)
330 //! assert_eq!(Utc::today(), Utc::now().date());
331 //! assert_eq!(Local::today(), Local::now().date());
332 //!
333 //! assert_eq!(Utc.ymd(2014, 11, 28).weekday(), Weekday::Fri);
334 //! assert_eq!(Utc.ymd_opt(2014, 11, 31), LocalResult::None);
335 //! assert_eq!(Utc.ymd(2014, 11, 28).and_hms_milli(7, 8, 9, 10).format("%H%M%S").to_string(),
336 //! "070809");
337 //! ```
338 //!
339 //! There is no timezone-aware `Time` due to the lack of usefulness and also the complexity.
340 //!
341 //! `DateTime` has [`date`](./struct.DateTime.html#method.date) method
342 //! which returns a `Date` which represents its date component.
343 //! There is also a [`time`](./struct.DateTime.html#method.time) method,
344 //! which simply returns a naive local time described below.
345 //!
346 //! ### Naive date and time
347 //!
348 //! Chrono provides naive counterparts to `Date`, (non-existent) `Time` and `DateTime`
349 //! as [**`NaiveDate`**](./naive/struct.NaiveDate.html),
350 //! [**`NaiveTime`**](./naive/struct.NaiveTime.html) and
351 //! [**`NaiveDateTime`**](./naive/struct.NaiveDateTime.html) respectively.
352 //!
353 //! They have almost equivalent interfaces as their timezone-aware twins,
354 //! but are not associated to time zones obviously and can be quite low-level.
355 //! They are mostly useful for building blocks for higher-level types.
356 //!
357 //! Timezone-aware `DateTime` and `Date` types have two methods returning naive versions:
358 //! [`naive_local`](./struct.DateTime.html#method.naive_local) returns
359 //! a view to the naive local time,
360 //! and [`naive_utc`](./struct.DateTime.html#method.naive_utc) returns
361 //! a view to the naive UTC time.
362 //!
363 //! ## Limitations
364 //!
365 //! Only proleptic Gregorian calendar (i.e. extended to support older dates) is supported.
366 //! Be very careful if you really have to deal with pre-20C dates, they can be in Julian or others.
367 //!
368 //! Date types are limited in about +/- 262,000 years from the common epoch.
369 //! Time types are limited in the nanosecond accuracy.
370 //!
371 //! [Leap seconds are supported in the representation but
372 //! Chrono doesn't try to make use of them](./naive/struct.NaiveTime.html#leap-second-handling).
373 //! (The main reason is that leap seconds are not really predictable.)
374 //! Almost *every* operation over the possible leap seconds will ignore them.
375 //! Consider using `NaiveDateTime` with the implicit TAI (International Atomic Time) scale
376 //! if you want.
377 //!
378 //! Chrono inherently does not support an inaccurate or partial date and time representation.
379 //! Any operation that can be ambiguous will return `None` in such cases.
380 //! For example, "a month later" of 2014-01-30 is not well-defined
381 //! and consequently `Utc.ymd(2014, 1, 30).with_month(2)` returns `None`.
382 //!
383 //! Advanced time zone handling is not yet supported.
384 //! For now you can try the [Chrono-tz](https://github.com/chronotope/chrono-tz/) crate instead.
385
386 #![doc(html_root_url = "https://docs.rs/chrono/latest/")]
387
388 #![cfg_attr(bench, feature(test))] // lib stability features as per RFC #507
389 #![deny(missing_docs)]
390 #![deny(missing_debug_implementations)]
391
392 // The explicit 'static lifetimes are still needed for rustc 1.13-16
393 // backward compatibility, and this appeases clippy. If minimum rustc
394 // becomes 1.17, should be able to remove this, those 'static lifetimes,
395 // and use `static` in a lot of places `const` is used now.
396 //
397 // Similarly, redundant_field_names lints on not using the
398 // field-init-shorthand, which was stabilized in rust 1.17.
399 //
400 // Changing trivially_copy_pass_by_ref would require an incompatible version
401 // bump.
402 #![cfg_attr(feature = "cargo-clippy", allow(
403 const_static_lifetime,
404 redundant_field_names,
405 trivially_copy_pass_by_ref,
406 ))]
407
408 #[cfg(feature="clock")]
409 extern crate time as oldtime;
410 extern crate num_integer;
411 extern crate num_traits;
412 #[cfg(feature = "rustc-serialize")]
413 extern crate rustc_serialize;
414 #[cfg(feature = "serde")]
415 extern crate serde as serdelib;
416
417 // this reexport is to aid the transition and should not be in the prelude!
418 pub use oldtime::Duration;
419
420 #[cfg(feature="clock")]
421 #[doc(no_inline)] pub use offset::Local;
422 #[doc(no_inline)] pub use offset::{TimeZone, Offset, LocalResult, Utc, FixedOffset};
423 #[doc(no_inline)] pub use naive::{NaiveDate, IsoWeek, NaiveTime, NaiveDateTime};
424 pub use date::{Date, MIN_DATE, MAX_DATE};
425 pub use datetime::{DateTime, SecondsFormat};
426 #[cfg(feature = "rustc-serialize")]
427 pub use datetime::rustc_serialize::TsSeconds;
428 pub use format::{ParseError, ParseResult};
429 pub use round::SubsecRound;
430
431 /// A convenience module appropriate for glob imports (`use chrono::prelude::*;`).
432 pub mod prelude {
433 #[doc(no_inline)] pub use {Datelike, Timelike, Weekday};
434 #[doc(no_inline)] pub use {TimeZone, Offset};
435 #[cfg(feature="clock")]
436 #[doc(no_inline)] pub use Local;
437 #[doc(no_inline)] pub use {Utc, FixedOffset};
438 #[doc(no_inline)] pub use {NaiveDate, NaiveTime, NaiveDateTime};
439 #[doc(no_inline)] pub use Date;
440 #[doc(no_inline)] pub use {DateTime, SecondsFormat};
441 #[doc(no_inline)] pub use SubsecRound;
442 }
443
444 // useful throughout the codebase
445 macro_rules! try_opt {
446 ($e:expr) => (match $e { Some(v) => v, None => return None })
447 }
448
449 mod div;
450 #[cfg(not(feature="clock"))]
451 mod oldtime;
452 pub mod offset;
453 pub mod naive {
454 //! Date and time types which do not concern about the timezones.
455 //!
456 //! They are primarily building blocks for other types
457 //! (e.g. [`TimeZone`](../offset/trait.TimeZone.html)),
458 //! but can be also used for the simpler date and time handling.
459
460 mod internals;
461 mod date;
462 mod isoweek;
463 mod time;
464 mod datetime;
465
466 pub use self::date::{NaiveDate, MIN_DATE, MAX_DATE};
467 pub use self::isoweek::IsoWeek;
468 pub use self::time::NaiveTime;
469 pub use self::datetime::NaiveDateTime;
470 #[cfg(feature = "rustc-serialize")]
471 #[allow(deprecated)]
472 pub use self::datetime::rustc_serialize::TsSeconds;
473
474
475 /// Serialization/Deserialization of naive types 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 mod date;
489 mod datetime;
490 pub mod format;
491 mod round;
492
493 /// Serialization/Deserialization in alternate formats
494 ///
495 /// The various modules in here are intended to be used with serde's [`with`
496 /// annotation][1] to serialize as something other than the default [RFC
497 /// 3339][2] format.
498 ///
499 /// [1]: https://serde.rs/attributes.html#field-attributes
500 /// [2]: https://tools.ietf.org/html/rfc3339
501 #[cfg(feature = "serde")]
502 pub mod serde {
503 pub use super::datetime::serde::*;
504 }
505
506 /// The day of week.
507 ///
508 /// The order of the days of week depends on the context.
509 /// (This is why this type does *not* implement `PartialOrd` or `Ord` traits.)
510 /// One should prefer `*_from_monday` or `*_from_sunday` methods to get the correct result.
511 #[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
512 #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
513 pub enum Weekday {
514 /// Monday.
515 Mon = 0,
516 /// Tuesday.
517 Tue = 1,
518 /// Wednesday.
519 Wed = 2,
520 /// Thursday.
521 Thu = 3,
522 /// Friday.
523 Fri = 4,
524 /// Saturday.
525 Sat = 5,
526 /// Sunday.
527 Sun = 6,
528 }
529
530 impl Weekday {
531 /// The next day in the week.
532 ///
533 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
534 /// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
535 /// `w.succ()`: | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun` | `Mon`
536 #[inline]
succ(&self) -> Weekday537 pub fn succ(&self) -> Weekday {
538 match *self {
539 Weekday::Mon => Weekday::Tue,
540 Weekday::Tue => Weekday::Wed,
541 Weekday::Wed => Weekday::Thu,
542 Weekday::Thu => Weekday::Fri,
543 Weekday::Fri => Weekday::Sat,
544 Weekday::Sat => Weekday::Sun,
545 Weekday::Sun => Weekday::Mon,
546 }
547 }
548
549 /// The previous day in the week.
550 ///
551 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
552 /// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
553 /// `w.pred()`: | `Sun` | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat`
554 #[inline]
pred(&self) -> Weekday555 pub fn pred(&self) -> Weekday {
556 match *self {
557 Weekday::Mon => Weekday::Sun,
558 Weekday::Tue => Weekday::Mon,
559 Weekday::Wed => Weekday::Tue,
560 Weekday::Thu => Weekday::Wed,
561 Weekday::Fri => Weekday::Thu,
562 Weekday::Sat => Weekday::Fri,
563 Weekday::Sun => Weekday::Sat,
564 }
565 }
566
567 /// Returns a day-of-week number starting from Monday = 1. (ISO 8601 weekday number)
568 ///
569 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
570 /// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
571 /// `w.number_from_monday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 7
572 #[inline]
number_from_monday(&self) -> u32573 pub fn number_from_monday(&self) -> u32 {
574 match *self {
575 Weekday::Mon => 1,
576 Weekday::Tue => 2,
577 Weekday::Wed => 3,
578 Weekday::Thu => 4,
579 Weekday::Fri => 5,
580 Weekday::Sat => 6,
581 Weekday::Sun => 7,
582 }
583 }
584
585 /// Returns a day-of-week number starting from Sunday = 1.
586 ///
587 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
588 /// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
589 /// `w.number_from_sunday()`: | 2 | 3 | 4 | 5 | 6 | 7 | 1
590 #[inline]
number_from_sunday(&self) -> u32591 pub fn number_from_sunday(&self) -> u32 {
592 match *self {
593 Weekday::Mon => 2,
594 Weekday::Tue => 3,
595 Weekday::Wed => 4,
596 Weekday::Thu => 5,
597 Weekday::Fri => 6,
598 Weekday::Sat => 7,
599 Weekday::Sun => 1,
600 }
601 }
602
603 /// Returns a day-of-week number starting from Monday = 0.
604 ///
605 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
606 /// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
607 /// `w.num_days_from_monday()`: | 0 | 1 | 2 | 3 | 4 | 5 | 6
608 #[inline]
num_days_from_monday(&self) -> u32609 pub fn num_days_from_monday(&self) -> u32 {
610 match *self {
611 Weekday::Mon => 0,
612 Weekday::Tue => 1,
613 Weekday::Wed => 2,
614 Weekday::Thu => 3,
615 Weekday::Fri => 4,
616 Weekday::Sat => 5,
617 Weekday::Sun => 6,
618 }
619 }
620
621 /// Returns a day-of-week number starting from Sunday = 0.
622 ///
623 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
624 /// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
625 /// `w.num_days_from_sunday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 0
626 #[inline]
num_days_from_sunday(&self) -> u32627 pub fn num_days_from_sunday(&self) -> u32 {
628 match *self {
629 Weekday::Mon => 1,
630 Weekday::Tue => 2,
631 Weekday::Wed => 3,
632 Weekday::Thu => 4,
633 Weekday::Fri => 5,
634 Weekday::Sat => 6,
635 Weekday::Sun => 0,
636 }
637 }
638 }
639
640 /// Any weekday can be represented as an integer from 0 to 6, which equals to
641 /// [`Weekday::num_days_from_monday`](#method.num_days_from_monday) in this implementation.
642 /// Do not heavily depend on this though; use explicit methods whenever possible.
643 impl num_traits::FromPrimitive for Weekday {
644 #[inline]
from_i64(n: i64) -> Option<Weekday>645 fn from_i64(n: i64) -> Option<Weekday> {
646 match n {
647 0 => Some(Weekday::Mon),
648 1 => Some(Weekday::Tue),
649 2 => Some(Weekday::Wed),
650 3 => Some(Weekday::Thu),
651 4 => Some(Weekday::Fri),
652 5 => Some(Weekday::Sat),
653 6 => Some(Weekday::Sun),
654 _ => None,
655 }
656 }
657
658 #[inline]
from_u64(n: u64) -> Option<Weekday>659 fn from_u64(n: u64) -> Option<Weekday> {
660 match n {
661 0 => Some(Weekday::Mon),
662 1 => Some(Weekday::Tue),
663 2 => Some(Weekday::Wed),
664 3 => Some(Weekday::Thu),
665 4 => Some(Weekday::Fri),
666 5 => Some(Weekday::Sat),
667 6 => Some(Weekday::Sun),
668 _ => None,
669 }
670 }
671 }
672
673 use std::fmt;
674
675 /// An error resulting from reading `Weekday` value with `FromStr`.
676 #[derive(Clone, PartialEq)]
677 pub struct ParseWeekdayError {
678 _dummy: (),
679 }
680
681 impl fmt::Debug for ParseWeekdayError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
683 write!(f, "ParseWeekdayError {{ .. }}")
684 }
685 }
686
687 // the actual `FromStr` implementation is in the `format` module to leverage the existing code
688
689 #[cfg(feature = "serde")]
690 mod weekday_serde {
691 use super::Weekday;
692 use std::fmt;
693 use serdelib::{ser, de};
694
695 impl ser::Serialize for Weekday {
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer696 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
697 where S: ser::Serializer
698 {
699 serializer.serialize_str(&format!("{:?}", self))
700 }
701 }
702
703 struct WeekdayVisitor;
704
705 impl<'de> de::Visitor<'de> for WeekdayVisitor {
706 type Value = Weekday;
707
expecting(&self, f: &mut fmt::Formatter) -> fmt::Result708 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
709 write!(f, "Weekday")
710 }
711
visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error712 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
713 where E: de::Error
714 {
715 value.parse().map_err(|_| E::custom("short or long weekday names expected"))
716 }
717 }
718
719 impl<'de> de::Deserialize<'de> for Weekday {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>720 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
721 where D: de::Deserializer<'de>
722 {
723 deserializer.deserialize_str(WeekdayVisitor)
724 }
725 }
726
727 #[cfg(test)]
728 extern crate serde_json;
729
730 #[test]
test_serde_serialize()731 fn test_serde_serialize() {
732 use self::serde_json::to_string;
733 use Weekday::*;
734
735 let cases: Vec<(Weekday, &str)> = vec![
736 (Mon, "\"Mon\""),
737 (Tue, "\"Tue\""),
738 (Wed, "\"Wed\""),
739 (Thu, "\"Thu\""),
740 (Fri, "\"Fri\""),
741 (Sat, "\"Sat\""),
742 (Sun, "\"Sun\""),
743 ];
744
745 for (weekday, expected_str) in cases {
746 let string = to_string(&weekday).unwrap();
747 assert_eq!(string, expected_str);
748 }
749 }
750
751 #[test]
test_serde_deserialize()752 fn test_serde_deserialize() {
753 use self::serde_json::from_str;
754 use Weekday::*;
755
756 let cases: Vec<(&str, Weekday)> = vec![
757 ("\"mon\"", Mon),
758 ("\"MONDAY\"", Mon),
759 ("\"MonDay\"", Mon),
760 ("\"mOn\"", Mon),
761 ("\"tue\"", Tue),
762 ("\"tuesday\"", Tue),
763 ("\"wed\"", Wed),
764 ("\"wednesday\"", Wed),
765 ("\"thu\"", Thu),
766 ("\"thursday\"", Thu),
767 ("\"fri\"", Fri),
768 ("\"friday\"", Fri),
769 ("\"sat\"", Sat),
770 ("\"saturday\"", Sat),
771 ("\"sun\"", Sun),
772 ("\"sunday\"", Sun),
773 ];
774
775 for (str, expected_weekday) in cases {
776 let weekday = from_str::<Weekday>(str).unwrap();
777 assert_eq!(weekday, expected_weekday);
778 }
779
780 let errors: Vec<&str> = vec![
781 "\"not a weekday\"",
782 "\"monDAYs\"",
783 "\"mond\"",
784 "mon",
785 "\"thur\"",
786 "\"thurs\"",
787 ];
788
789 for str in errors {
790 from_str::<Weekday>(str).unwrap_err();
791 }
792 }
793 }
794
795 /// The common set of methods for date component.
796 pub trait Datelike: Sized {
797 /// Returns the year number in the [calendar date](./naive/struct.NaiveDate.html#calendar-date).
year(&self) -> i32798 fn year(&self) -> i32;
799
800 /// Returns the absolute year number starting from 1 with a boolean flag,
801 /// which is false when the year predates the epoch (BCE/BC) and true otherwise (CE/AD).
802 #[inline]
year_ce(&self) -> (bool, u32)803 fn year_ce(&self) -> (bool, u32) {
804 let year = self.year();
805 if year < 1 {
806 (false, (1 - year) as u32)
807 } else {
808 (true, year as u32)
809 }
810 }
811
812 /// Returns the month number starting from 1.
813 ///
814 /// The return value ranges from 1 to 12.
month(&self) -> u32815 fn month(&self) -> u32;
816
817 /// Returns the month number starting from 0.
818 ///
819 /// The return value ranges from 0 to 11.
month0(&self) -> u32820 fn month0(&self) -> u32;
821
822 /// Returns the day of month starting from 1.
823 ///
824 /// The return value ranges from 1 to 31. (The last day of month differs by months.)
day(&self) -> u32825 fn day(&self) -> u32;
826
827 /// Returns the day of month starting from 0.
828 ///
829 /// The return value ranges from 0 to 30. (The last day of month differs by months.)
day0(&self) -> u32830 fn day0(&self) -> u32;
831
832 /// Returns the day of year starting from 1.
833 ///
834 /// The return value ranges from 1 to 366. (The last day of year differs by years.)
ordinal(&self) -> u32835 fn ordinal(&self) -> u32;
836
837 /// Returns the day of year starting from 0.
838 ///
839 /// The return value ranges from 0 to 365. (The last day of year differs by years.)
ordinal0(&self) -> u32840 fn ordinal0(&self) -> u32;
841
842 /// Returns the day of week.
weekday(&self) -> Weekday843 fn weekday(&self) -> Weekday;
844
845 /// Returns the ISO week.
iso_week(&self) -> IsoWeek846 fn iso_week(&self) -> IsoWeek;
847
848 /// Makes a new value with the year number changed.
849 ///
850 /// Returns `None` when the resulting value would be invalid.
with_year(&self, year: i32) -> Option<Self>851 fn with_year(&self, year: i32) -> Option<Self>;
852
853 /// Makes a new value with the month number (starting from 1) changed.
854 ///
855 /// Returns `None` when the resulting value would be invalid.
with_month(&self, month: u32) -> Option<Self>856 fn with_month(&self, month: u32) -> Option<Self>;
857
858 /// Makes a new value with the month number (starting from 0) changed.
859 ///
860 /// Returns `None` when the resulting value would be invalid.
with_month0(&self, month0: u32) -> Option<Self>861 fn with_month0(&self, month0: u32) -> Option<Self>;
862
863 /// Makes a new value with the day of month (starting from 1) changed.
864 ///
865 /// Returns `None` when the resulting value would be invalid.
with_day(&self, day: u32) -> Option<Self>866 fn with_day(&self, day: u32) -> Option<Self>;
867
868 /// Makes a new value with the day of month (starting from 0) changed.
869 ///
870 /// Returns `None` when the resulting value would be invalid.
with_day0(&self, day0: u32) -> Option<Self>871 fn with_day0(&self, day0: u32) -> Option<Self>;
872
873 /// Makes a new value with the day of year (starting from 1) changed.
874 ///
875 /// Returns `None` when the resulting value would be invalid.
with_ordinal(&self, ordinal: u32) -> Option<Self>876 fn with_ordinal(&self, ordinal: u32) -> Option<Self>;
877
878 /// Makes a new value with the day of year (starting from 0) changed.
879 ///
880 /// Returns `None` when the resulting value would be invalid.
with_ordinal0(&self, ordinal0: u32) -> Option<Self>881 fn with_ordinal0(&self, ordinal0: u32) -> Option<Self>;
882
883 /// Returns the number of days since January 1, Year 1 (aka Day 1) in the
884 /// proleptic Gregorian calendar.
885 ///
886 /// # Example:
887 ///
888 /// ~~~
889 /// use chrono::{NaiveDate, Datelike};
890 /// assert_eq!(NaiveDate::from_ymd(1970, 1, 1).num_days_from_ce(), 719163);
891 /// assert_eq!(NaiveDate::from_ymd(0, 1, 1).num_days_from_ce(), -365);
892 /// ~~~
num_days_from_ce(&self) -> i32893 fn num_days_from_ce(&self) -> i32 {
894 // we know this wouldn't overflow since year is limited to 1/2^13 of i32's full range.
895 let mut year = self.year() - 1;
896 let mut ndays = 0;
897 if year < 0 {
898 let excess = 1 + (-year) / 400;
899 year += excess * 400;
900 ndays -= excess * 146_097;
901 }
902 let div_100 = year / 100;
903 ndays += ((year * 1461) >> 2) - div_100 + (div_100 >> 2);
904 ndays + self.ordinal() as i32
905 }
906 }
907
908 /// The common set of methods for time component.
909 pub trait Timelike: Sized {
910 /// Returns the hour number from 0 to 23.
hour(&self) -> u32911 fn hour(&self) -> u32;
912
913 /// Returns the hour number from 1 to 12 with a boolean flag,
914 /// which is false for AM and true for PM.
915 #[inline]
hour12(&self) -> (bool, u32)916 fn hour12(&self) -> (bool, u32) {
917 let hour = self.hour();
918 let mut hour12 = hour % 12;
919 if hour12 == 0 {
920 hour12 = 12;
921 }
922 (hour >= 12, hour12)
923 }
924
925 /// Returns the minute number from 0 to 59.
minute(&self) -> u32926 fn minute(&self) -> u32;
927
928 /// Returns the second number from 0 to 59.
second(&self) -> u32929 fn second(&self) -> u32;
930
931 /// Returns the number of nanoseconds since the whole non-leap second.
932 /// The range from 1,000,000,000 to 1,999,999,999 represents
933 /// the [leap second](./naive/struct.NaiveTime.html#leap-second-handling).
nanosecond(&self) -> u32934 fn nanosecond(&self) -> u32;
935
936 /// Makes a new value with the hour number changed.
937 ///
938 /// Returns `None` when the resulting value would be invalid.
with_hour(&self, hour: u32) -> Option<Self>939 fn with_hour(&self, hour: u32) -> Option<Self>;
940
941 /// Makes a new value with the minute number changed.
942 ///
943 /// Returns `None` when the resulting value would be invalid.
with_minute(&self, min: u32) -> Option<Self>944 fn with_minute(&self, min: u32) -> Option<Self>;
945
946 /// Makes a new value with the second number changed.
947 ///
948 /// Returns `None` when the resulting value would be invalid.
949 /// As with the [`second`](#tymethod.second) method,
950 /// the input range is restricted to 0 through 59.
with_second(&self, sec: u32) -> Option<Self>951 fn with_second(&self, sec: u32) -> Option<Self>;
952
953 /// Makes a new value with nanoseconds since the whole non-leap second changed.
954 ///
955 /// Returns `None` when the resulting value would be invalid.
956 /// As with the [`nanosecond`](#tymethod.nanosecond) method,
957 /// the input range can exceed 1,000,000,000 for leap seconds.
with_nanosecond(&self, nano: u32) -> Option<Self>958 fn with_nanosecond(&self, nano: u32) -> Option<Self>;
959
960 /// Returns the number of non-leap seconds past the last midnight.
961 #[inline]
num_seconds_from_midnight(&self) -> u32962 fn num_seconds_from_midnight(&self) -> u32 {
963 self.hour() * 3600 + self.minute() * 60 + self.second()
964 }
965 }
966
967 #[cfg(test)] extern crate num_iter;
968
969 #[test]
test_readme_doomsday()970 fn test_readme_doomsday() {
971 use num_iter::range_inclusive;
972
973 for y in range_inclusive(naive::MIN_DATE.year(), naive::MAX_DATE.year()) {
974 // even months
975 let d4 = NaiveDate::from_ymd(y, 4, 4);
976 let d6 = NaiveDate::from_ymd(y, 6, 6);
977 let d8 = NaiveDate::from_ymd(y, 8, 8);
978 let d10 = NaiveDate::from_ymd(y, 10, 10);
979 let d12 = NaiveDate::from_ymd(y, 12, 12);
980
981 // nine to five, seven-eleven
982 let d59 = NaiveDate::from_ymd(y, 5, 9);
983 let d95 = NaiveDate::from_ymd(y, 9, 5);
984 let d711 = NaiveDate::from_ymd(y, 7, 11);
985 let d117 = NaiveDate::from_ymd(y, 11, 7);
986
987 // "March 0"
988 let d30 = NaiveDate::from_ymd(y, 3, 1).pred();
989
990 let weekday = d30.weekday();
991 let other_dates = [d4, d6, d8, d10, d12, d59, d95, d711, d117];
992 assert!(other_dates.iter().all(|d| d.weekday() == weekday));
993 }
994 }
995