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;
162 //! extern crate time;
163 //!
164 //! # fn main() {
165 //! use chrono::prelude::*;
166 //! use time::Duration;
167 //!
168 //! // assume this returned `2014-11-28T21:45:59.324310806+09:00`:
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 //! // We need the trait in scope to use Utc::timestamp().
306 //! use chrono::{DateTime, TimeZone, Utc};
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/latest/")]
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 //
398 // Changing trivially_copy_pass_by_ref would require an incompatible version
399 // bump.
400 #![cfg_attr(feature = "cargo-clippy", allow(
401 const_static_lifetime,
402 redundant_field_names,
403 trivially_copy_pass_by_ref,
404 ))]
405
406 #[cfg(feature="clock")]
407 extern crate time as oldtime;
408 extern crate num_integer;
409 extern crate num_traits;
410 #[cfg(feature = "rustc-serialize")]
411 extern crate rustc_serialize;
412 #[cfg(feature = "serde")]
413 extern crate serde as serdelib;
414 #[cfg(test)]
415 #[macro_use]
416 extern crate doc_comment;
417
418 #[cfg(test)]
419 doctest!("../README.md");
420
421 // this reexport is to aid the transition and should not be in the prelude!
422 pub use oldtime::Duration;
423
424 #[cfg(feature="clock")]
425 #[doc(no_inline)] pub use offset::Local;
426 #[doc(no_inline)] pub use offset::{TimeZone, Offset, LocalResult, Utc, FixedOffset};
427 #[doc(no_inline)] pub use naive::{NaiveDate, IsoWeek, NaiveTime, NaiveDateTime};
428 pub use date::{Date, MIN_DATE, MAX_DATE};
429 pub use datetime::{DateTime, SecondsFormat};
430 #[cfg(feature = "rustc-serialize")]
431 pub use datetime::rustc_serialize::TsSeconds;
432 pub use format::{ParseError, ParseResult};
433 pub use round::SubsecRound;
434
435 /// A convenience module appropriate for glob imports (`use chrono::prelude::*;`).
436 pub mod prelude {
437 #[doc(no_inline)] pub use {Datelike, Timelike, Weekday};
438 #[doc(no_inline)] pub use {TimeZone, Offset};
439 #[cfg(feature="clock")]
440 #[doc(no_inline)] pub use Local;
441 #[doc(no_inline)] pub use {Utc, FixedOffset};
442 #[doc(no_inline)] pub use {NaiveDate, NaiveTime, NaiveDateTime};
443 #[doc(no_inline)] pub use Date;
444 #[doc(no_inline)] pub use {DateTime, SecondsFormat};
445 #[doc(no_inline)] pub use SubsecRound;
446 }
447
448 // useful throughout the codebase
449 macro_rules! try_opt {
450 ($e:expr) => (match $e { Some(v) => v, None => return None })
451 }
452
453 mod div;
454 #[cfg(not(feature="clock"))]
455 mod oldtime;
456 pub mod offset;
457 pub mod naive {
458 //! Date and time types unconcerned with timezones.
459 //!
460 //! They are primarily building blocks for other types
461 //! (e.g. [`TimeZone`](../offset/trait.TimeZone.html)),
462 //! but can be also used for the simpler date and time handling.
463
464 mod internals;
465 mod date;
466 mod isoweek;
467 mod time;
468 mod datetime;
469
470 pub use self::date::{NaiveDate, MIN_DATE, MAX_DATE};
471 pub use self::isoweek::IsoWeek;
472 pub use self::time::NaiveTime;
473 pub use self::datetime::NaiveDateTime;
474 #[cfg(feature = "rustc-serialize")]
475 #[allow(deprecated)]
476 pub use self::datetime::rustc_serialize::TsSeconds;
477
478
479 /// Serialization/Deserialization of naive types in alternate formats
480 ///
481 /// The various modules in here are intended to be used with serde's [`with`
482 /// annotation][1] to serialize as something other than the default [RFC
483 /// 3339][2] format.
484 ///
485 /// [1]: https://serde.rs/attributes.html#field-attributes
486 /// [2]: https://tools.ietf.org/html/rfc3339
487 #[cfg(feature = "serde")]
488 pub mod serde {
489 pub use super::datetime::serde::*;
490 }
491 }
492 mod date;
493 mod datetime;
494 pub mod format;
495 mod round;
496
497 /// Serialization/Deserialization in alternate formats
498 ///
499 /// The various modules in here are intended to be used with serde's [`with`
500 /// annotation][1] to serialize as something other than the default [RFC
501 /// 3339][2] format.
502 ///
503 /// [1]: https://serde.rs/attributes.html#field-attributes
504 /// [2]: https://tools.ietf.org/html/rfc3339
505 #[cfg(feature = "serde")]
506 pub mod serde {
507 pub use super::datetime::serde::*;
508 }
509
510 /// The day of week.
511 ///
512 /// The order of the days of week depends on the context.
513 /// (This is why this type does *not* implement `PartialOrd` or `Ord` traits.)
514 /// One should prefer `*_from_monday` or `*_from_sunday` methods to get the correct result.
515 #[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
516 #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
517 pub enum Weekday {
518 /// Monday.
519 Mon = 0,
520 /// Tuesday.
521 Tue = 1,
522 /// Wednesday.
523 Wed = 2,
524 /// Thursday.
525 Thu = 3,
526 /// Friday.
527 Fri = 4,
528 /// Saturday.
529 Sat = 5,
530 /// Sunday.
531 Sun = 6,
532 }
533
534 impl Weekday {
535 /// The next day in the week.
536 ///
537 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
538 /// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
539 /// `w.succ()`: | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun` | `Mon`
540 #[inline]
succ(&self) -> Weekday541 pub fn succ(&self) -> Weekday {
542 match *self {
543 Weekday::Mon => Weekday::Tue,
544 Weekday::Tue => Weekday::Wed,
545 Weekday::Wed => Weekday::Thu,
546 Weekday::Thu => Weekday::Fri,
547 Weekday::Fri => Weekday::Sat,
548 Weekday::Sat => Weekday::Sun,
549 Weekday::Sun => Weekday::Mon,
550 }
551 }
552
553 /// The previous day in the week.
554 ///
555 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
556 /// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
557 /// `w.pred()`: | `Sun` | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat`
558 #[inline]
pred(&self) -> Weekday559 pub fn pred(&self) -> Weekday {
560 match *self {
561 Weekday::Mon => Weekday::Sun,
562 Weekday::Tue => Weekday::Mon,
563 Weekday::Wed => Weekday::Tue,
564 Weekday::Thu => Weekday::Wed,
565 Weekday::Fri => Weekday::Thu,
566 Weekday::Sat => Weekday::Fri,
567 Weekday::Sun => Weekday::Sat,
568 }
569 }
570
571 /// Returns a day-of-week number starting from Monday = 1. (ISO 8601 weekday number)
572 ///
573 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
574 /// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
575 /// `w.number_from_monday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 7
576 #[inline]
number_from_monday(&self) -> u32577 pub fn number_from_monday(&self) -> u32 {
578 match *self {
579 Weekday::Mon => 1,
580 Weekday::Tue => 2,
581 Weekday::Wed => 3,
582 Weekday::Thu => 4,
583 Weekday::Fri => 5,
584 Weekday::Sat => 6,
585 Weekday::Sun => 7,
586 }
587 }
588
589 /// Returns a day-of-week number starting from Sunday = 1.
590 ///
591 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
592 /// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
593 /// `w.number_from_sunday()`: | 2 | 3 | 4 | 5 | 6 | 7 | 1
594 #[inline]
number_from_sunday(&self) -> u32595 pub fn number_from_sunday(&self) -> u32 {
596 match *self {
597 Weekday::Mon => 2,
598 Weekday::Tue => 3,
599 Weekday::Wed => 4,
600 Weekday::Thu => 5,
601 Weekday::Fri => 6,
602 Weekday::Sat => 7,
603 Weekday::Sun => 1,
604 }
605 }
606
607 /// Returns a day-of-week number starting from Monday = 0.
608 ///
609 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
610 /// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
611 /// `w.num_days_from_monday()`: | 0 | 1 | 2 | 3 | 4 | 5 | 6
612 #[inline]
num_days_from_monday(&self) -> u32613 pub fn num_days_from_monday(&self) -> u32 {
614 match *self {
615 Weekday::Mon => 0,
616 Weekday::Tue => 1,
617 Weekday::Wed => 2,
618 Weekday::Thu => 3,
619 Weekday::Fri => 4,
620 Weekday::Sat => 5,
621 Weekday::Sun => 6,
622 }
623 }
624
625 /// Returns a day-of-week number starting from Sunday = 0.
626 ///
627 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
628 /// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
629 /// `w.num_days_from_sunday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 0
630 #[inline]
num_days_from_sunday(&self) -> u32631 pub fn num_days_from_sunday(&self) -> u32 {
632 match *self {
633 Weekday::Mon => 1,
634 Weekday::Tue => 2,
635 Weekday::Wed => 3,
636 Weekday::Thu => 4,
637 Weekday::Fri => 5,
638 Weekday::Sat => 6,
639 Weekday::Sun => 0,
640 }
641 }
642 }
643
644 /// Any weekday can be represented as an integer from 0 to 6, which equals to
645 /// [`Weekday::num_days_from_monday`](#method.num_days_from_monday) in this implementation.
646 /// Do not heavily depend on this though; use explicit methods whenever possible.
647 impl num_traits::FromPrimitive for Weekday {
648 #[inline]
from_i64(n: i64) -> Option<Weekday>649 fn from_i64(n: i64) -> Option<Weekday> {
650 match n {
651 0 => Some(Weekday::Mon),
652 1 => Some(Weekday::Tue),
653 2 => Some(Weekday::Wed),
654 3 => Some(Weekday::Thu),
655 4 => Some(Weekday::Fri),
656 5 => Some(Weekday::Sat),
657 6 => Some(Weekday::Sun),
658 _ => None,
659 }
660 }
661
662 #[inline]
from_u64(n: u64) -> Option<Weekday>663 fn from_u64(n: u64) -> Option<Weekday> {
664 match n {
665 0 => Some(Weekday::Mon),
666 1 => Some(Weekday::Tue),
667 2 => Some(Weekday::Wed),
668 3 => Some(Weekday::Thu),
669 4 => Some(Weekday::Fri),
670 5 => Some(Weekday::Sat),
671 6 => Some(Weekday::Sun),
672 _ => None,
673 }
674 }
675 }
676
677 use std::fmt;
678
679 /// An error resulting from reading `Weekday` value with `FromStr`.
680 #[derive(Clone, PartialEq)]
681 pub struct ParseWeekdayError {
682 _dummy: (),
683 }
684
685 impl fmt::Debug for ParseWeekdayError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result686 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
687 write!(f, "ParseWeekdayError {{ .. }}")
688 }
689 }
690
691 // the actual `FromStr` implementation is in the `format` module to leverage the existing code
692
693 #[cfg(feature = "serde")]
694 mod weekday_serde {
695 use super::Weekday;
696 use std::fmt;
697 use serdelib::{ser, de};
698
699 impl ser::Serialize for Weekday {
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer700 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
701 where S: ser::Serializer
702 {
703 serializer.serialize_str(&format!("{:?}", self))
704 }
705 }
706
707 struct WeekdayVisitor;
708
709 impl<'de> de::Visitor<'de> for WeekdayVisitor {
710 type Value = Weekday;
711
expecting(&self, f: &mut fmt::Formatter) -> fmt::Result712 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
713 write!(f, "Weekday")
714 }
715
visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error716 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
717 where E: de::Error
718 {
719 value.parse().map_err(|_| E::custom("short or long weekday names expected"))
720 }
721 }
722
723 impl<'de> de::Deserialize<'de> for Weekday {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>724 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
725 where D: de::Deserializer<'de>
726 {
727 deserializer.deserialize_str(WeekdayVisitor)
728 }
729 }
730
731 #[cfg(test)]
732 extern crate serde_json;
733
734 #[test]
test_serde_serialize()735 fn test_serde_serialize() {
736 use self::serde_json::to_string;
737 use Weekday::*;
738
739 let cases: Vec<(Weekday, &str)> = vec![
740 (Mon, "\"Mon\""),
741 (Tue, "\"Tue\""),
742 (Wed, "\"Wed\""),
743 (Thu, "\"Thu\""),
744 (Fri, "\"Fri\""),
745 (Sat, "\"Sat\""),
746 (Sun, "\"Sun\""),
747 ];
748
749 for (weekday, expected_str) in cases {
750 let string = to_string(&weekday).unwrap();
751 assert_eq!(string, expected_str);
752 }
753 }
754
755 #[test]
test_serde_deserialize()756 fn test_serde_deserialize() {
757 use self::serde_json::from_str;
758 use Weekday::*;
759
760 let cases: Vec<(&str, Weekday)> = vec![
761 ("\"mon\"", Mon),
762 ("\"MONDAY\"", Mon),
763 ("\"MonDay\"", Mon),
764 ("\"mOn\"", Mon),
765 ("\"tue\"", Tue),
766 ("\"tuesday\"", Tue),
767 ("\"wed\"", Wed),
768 ("\"wednesday\"", Wed),
769 ("\"thu\"", Thu),
770 ("\"thursday\"", Thu),
771 ("\"fri\"", Fri),
772 ("\"friday\"", Fri),
773 ("\"sat\"", Sat),
774 ("\"saturday\"", Sat),
775 ("\"sun\"", Sun),
776 ("\"sunday\"", Sun),
777 ];
778
779 for (str, expected_weekday) in cases {
780 let weekday = from_str::<Weekday>(str).unwrap();
781 assert_eq!(weekday, expected_weekday);
782 }
783
784 let errors: Vec<&str> = vec![
785 "\"not a weekday\"",
786 "\"monDAYs\"",
787 "\"mond\"",
788 "mon",
789 "\"thur\"",
790 "\"thurs\"",
791 ];
792
793 for str in errors {
794 from_str::<Weekday>(str).unwrap_err();
795 }
796 }
797 }
798
799 /// The common set of methods for date component.
800 pub trait Datelike: Sized {
801 /// Returns the year number in the [calendar date](./naive/struct.NaiveDate.html#calendar-date).
year(&self) -> i32802 fn year(&self) -> i32;
803
804 /// Returns the absolute year number starting from 1 with a boolean flag,
805 /// which is false when the year predates the epoch (BCE/BC) and true otherwise (CE/AD).
806 #[inline]
year_ce(&self) -> (bool, u32)807 fn year_ce(&self) -> (bool, u32) {
808 let year = self.year();
809 if year < 1 {
810 (false, (1 - year) as u32)
811 } else {
812 (true, year as u32)
813 }
814 }
815
816 /// Returns the month number starting from 1.
817 ///
818 /// The return value ranges from 1 to 12.
month(&self) -> u32819 fn month(&self) -> u32;
820
821 /// Returns the month number starting from 0.
822 ///
823 /// The return value ranges from 0 to 11.
month0(&self) -> u32824 fn month0(&self) -> u32;
825
826 /// Returns the day of month starting from 1.
827 ///
828 /// The return value ranges from 1 to 31. (The last day of month differs by months.)
day(&self) -> u32829 fn day(&self) -> u32;
830
831 /// Returns the day of month starting from 0.
832 ///
833 /// The return value ranges from 0 to 30. (The last day of month differs by months.)
day0(&self) -> u32834 fn day0(&self) -> u32;
835
836 /// Returns the day of year starting from 1.
837 ///
838 /// The return value ranges from 1 to 366. (The last day of year differs by years.)
ordinal(&self) -> u32839 fn ordinal(&self) -> u32;
840
841 /// Returns the day of year starting from 0.
842 ///
843 /// The return value ranges from 0 to 365. (The last day of year differs by years.)
ordinal0(&self) -> u32844 fn ordinal0(&self) -> u32;
845
846 /// Returns the day of week.
weekday(&self) -> Weekday847 fn weekday(&self) -> Weekday;
848
849 /// Returns the ISO week.
iso_week(&self) -> IsoWeek850 fn iso_week(&self) -> IsoWeek;
851
852 /// Makes a new value with the year number changed.
853 ///
854 /// Returns `None` when the resulting value would be invalid.
with_year(&self, year: i32) -> Option<Self>855 fn with_year(&self, year: i32) -> Option<Self>;
856
857 /// Makes a new value with the month number (starting from 1) changed.
858 ///
859 /// Returns `None` when the resulting value would be invalid.
with_month(&self, month: u32) -> Option<Self>860 fn with_month(&self, month: u32) -> Option<Self>;
861
862 /// Makes a new value with the month number (starting from 0) changed.
863 ///
864 /// Returns `None` when the resulting value would be invalid.
with_month0(&self, month0: u32) -> Option<Self>865 fn with_month0(&self, month0: u32) -> Option<Self>;
866
867 /// Makes a new value with the day of month (starting from 1) changed.
868 ///
869 /// Returns `None` when the resulting value would be invalid.
with_day(&self, day: u32) -> Option<Self>870 fn with_day(&self, day: u32) -> Option<Self>;
871
872 /// Makes a new value with the day of month (starting from 0) changed.
873 ///
874 /// Returns `None` when the resulting value would be invalid.
with_day0(&self, day0: u32) -> Option<Self>875 fn with_day0(&self, day0: u32) -> Option<Self>;
876
877 /// Makes a new value with the day of year (starting from 1) changed.
878 ///
879 /// Returns `None` when the resulting value would be invalid.
with_ordinal(&self, ordinal: u32) -> Option<Self>880 fn with_ordinal(&self, ordinal: u32) -> Option<Self>;
881
882 /// Makes a new value with the day of year (starting from 0) changed.
883 ///
884 /// Returns `None` when the resulting value would be invalid.
with_ordinal0(&self, ordinal0: u32) -> Option<Self>885 fn with_ordinal0(&self, ordinal0: u32) -> Option<Self>;
886
887 /// Returns the number of days since January 1, Year 1 (aka Day 1) in the
888 /// proleptic Gregorian calendar.
889 ///
890 /// # Example:
891 ///
892 /// ~~~
893 /// use chrono::{NaiveDate, Datelike};
894 /// assert_eq!(NaiveDate::from_ymd(1970, 1, 1).num_days_from_ce(), 719163);
895 /// assert_eq!(NaiveDate::from_ymd(0, 1, 1).num_days_from_ce(), -365);
896 /// ~~~
num_days_from_ce(&self) -> i32897 fn num_days_from_ce(&self) -> i32 {
898 // we know this wouldn't overflow since year is limited to 1/2^13 of i32's full range.
899 let mut year = self.year() - 1;
900 let mut ndays = 0;
901 if year < 0 {
902 let excess = 1 + (-year) / 400;
903 year += excess * 400;
904 ndays -= excess * 146_097;
905 }
906 let div_100 = year / 100;
907 ndays += ((year * 1461) >> 2) - div_100 + (div_100 >> 2);
908 ndays + self.ordinal() as i32
909 }
910 }
911
912 /// The common set of methods for time component.
913 pub trait Timelike: Sized {
914 /// Returns the hour number from 0 to 23.
hour(&self) -> u32915 fn hour(&self) -> u32;
916
917 /// Returns the hour number from 1 to 12 with a boolean flag,
918 /// which is false for AM and true for PM.
919 #[inline]
hour12(&self) -> (bool, u32)920 fn hour12(&self) -> (bool, u32) {
921 let hour = self.hour();
922 let mut hour12 = hour % 12;
923 if hour12 == 0 {
924 hour12 = 12;
925 }
926 (hour >= 12, hour12)
927 }
928
929 /// Returns the minute number from 0 to 59.
minute(&self) -> u32930 fn minute(&self) -> u32;
931
932 /// Returns the second number from 0 to 59.
second(&self) -> u32933 fn second(&self) -> u32;
934
935 /// Returns the number of nanoseconds since the whole non-leap second.
936 /// The range from 1,000,000,000 to 1,999,999,999 represents
937 /// the [leap second](./naive/struct.NaiveTime.html#leap-second-handling).
nanosecond(&self) -> u32938 fn nanosecond(&self) -> u32;
939
940 /// Makes a new value with the hour number changed.
941 ///
942 /// Returns `None` when the resulting value would be invalid.
with_hour(&self, hour: u32) -> Option<Self>943 fn with_hour(&self, hour: u32) -> Option<Self>;
944
945 /// Makes a new value with the minute number changed.
946 ///
947 /// Returns `None` when the resulting value would be invalid.
with_minute(&self, min: u32) -> Option<Self>948 fn with_minute(&self, min: u32) -> Option<Self>;
949
950 /// Makes a new value with the second number changed.
951 ///
952 /// Returns `None` when the resulting value would be invalid.
953 /// As with the [`second`](#tymethod.second) method,
954 /// the input range is restricted to 0 through 59.
with_second(&self, sec: u32) -> Option<Self>955 fn with_second(&self, sec: u32) -> Option<Self>;
956
957 /// Makes a new value with nanoseconds since the whole non-leap second changed.
958 ///
959 /// Returns `None` when the resulting value would be invalid.
960 /// As with the [`nanosecond`](#tymethod.nanosecond) method,
961 /// the input range can exceed 1,000,000,000 for leap seconds.
with_nanosecond(&self, nano: u32) -> Option<Self>962 fn with_nanosecond(&self, nano: u32) -> Option<Self>;
963
964 /// Returns the number of non-leap seconds past the last midnight.
965 #[inline]
num_seconds_from_midnight(&self) -> u32966 fn num_seconds_from_midnight(&self) -> u32 {
967 self.hour() * 3600 + self.minute() * 60 + self.second()
968 }
969 }
970
971 #[cfg(test)] extern crate num_iter;
972
973 #[test]
test_readme_doomsday()974 fn test_readme_doomsday() {
975 use num_iter::range_inclusive;
976
977 for y in range_inclusive(naive::MIN_DATE.year(), naive::MAX_DATE.year()) {
978 // even months
979 let d4 = NaiveDate::from_ymd(y, 4, 4);
980 let d6 = NaiveDate::from_ymd(y, 6, 6);
981 let d8 = NaiveDate::from_ymd(y, 8, 8);
982 let d10 = NaiveDate::from_ymd(y, 10, 10);
983 let d12 = NaiveDate::from_ymd(y, 12, 12);
984
985 // nine to five, seven-eleven
986 let d59 = NaiveDate::from_ymd(y, 5, 9);
987 let d95 = NaiveDate::from_ymd(y, 9, 5);
988 let d711 = NaiveDate::from_ymd(y, 7, 11);
989 let d117 = NaiveDate::from_ymd(y, 11, 7);
990
991 // "March 0"
992 let d30 = NaiveDate::from_ymd(y, 3, 1).pred();
993
994 let weekday = d30.weekday();
995 let other_dates = [d4, d6, d8, d10, d12, d59, d95, d711, d117];
996 assert!(other_dates.iter().all(|d| d.weekday() == weekday));
997 }
998 }
999