1 // This is a part of Chrono.
2 // See README.md and LICENSE.txt for details.
6 //! Date and time handling for Rust.
7 //! It aims to be a feature-complete superset of
8 //! the [time](https://github.com/rust-lang-deprecated/time) library.
11 //! * Chrono strictly adheres to ISO 8601.
12 //! * Chrono is timezone-aware by default, with separate timezone-naive types.
13 //! * Chrono is space-optimal and (while not being the primary goal) reasonably efficient.
15 //! There were several previous attempts to bring a good date and time library to Rust,
16 //! which Chrono builds upon and should acknowledge:
18 //! * [Initial research on
19 //! the wiki](https://github.com/rust-lang/rust-wiki-backup/blob/master/Lib-datetime.md)
20 //! * Dietrich Epp's [datetime-rs](https://github.com/depp/datetime-rs)
21 //! * Luis de Bethencourt's [rust-datetime](https://github.com/luisbg/rust-datetime)
23 //! Any significant changes to Chrono are documented in
24 //! the [`CHANGELOG.md`](https://github.com/chronotope/chrono/blob/master/CHANGELOG.md) file.
28 //! Put this in your `Cargo.toml`:
35 //! Or, if you want [Serde](https://github.com/serde-rs/serde) or
36 //! [rustc-serialize](https://github.com/rust-lang-nursery/rustc-serialize) support,
37 //! include the features like this:
41 //! chrono = { version = "0.4", features = ["serde", "rustc-serialize"] }
44 //! > Note that Chrono's support for rustc-serialize is now considered deprecated.
45 //! Starting from 0.4.0 there is no further guarantee that
46 //! the features available in Serde will be also available to rustc-serialize,
47 //! and the support can be removed in any future major version.
48 //! **Rustc-serialize users are strongly recommended to migrate to Serde.**
50 //! Then put this in your crate root:
53 //! extern crate chrono;
56 //! Avoid using `use chrono::*;` as Chrono exports several modules other than types.
57 //! If you prefer the glob imports, use the following instead:
60 //! use chrono::prelude::*;
67 //! Chrono currently uses
68 //! the [`time::Duration`](https://doc.rust-lang.org/time/time/struct.Duration.html) type
69 //! from the `time` crate to represent the magnitude of a time span.
70 //! Since this has the same name to the newer, standard type for duration,
71 //! the reference will refer this type as `OldDuration`.
72 //! Note that this is an "accurate" duration represented as seconds and
73 //! nanoseconds and does not represent "nominal" components such as days or
76 //! Chrono does not yet natively support
77 //! the standard [`Duration`](https://doc.rust-lang.org/std/time/struct.Duration.html) type,
78 //! but it will be supported in the future.
79 //! Meanwhile you can convert between two types with
80 //! [`Duration::from_std`](https://doc.rust-lang.org/time/time/struct.Duration.html#method.from_std)
82 //! [`Duration::to_std`](https://doc.rust-lang.org/time/time/struct.Duration.html#method.to_std)
88 //! [**`DateTime`**](./struct.DateTime.html)
89 //! type to represent a date and a time in a timezone.
91 //! For more abstract moment-in-time tracking such as internal timekeeping
92 //! that is unconcerned with timezones, consider
93 //! [`time::SystemTime`](https://doc.rust-lang.org/std/time/struct.SystemTime.html),
94 //! which tracks your system clock, or
95 //! [`time::Instant`](https://doc.rust-lang.org/std/time/struct.Instant.html), which
96 //! is an opaque but monotonically-increasing representation of a moment in time.
98 //! `DateTime` is timezone-aware and must be constructed from
99 //! the [**`TimeZone`**](./offset/trait.TimeZone.html) object,
100 //! which defines how the local date is converted to and back from the UTC date.
101 //! There are three well-known `TimeZone` implementations:
103 //! * [**`Utc`**](./offset/struct.Utc.html) specifies the UTC time zone. It is most efficient.
105 //! * [**`Local`**](./offset/struct.Local.html) specifies the system local time zone.
107 //! * [**`FixedOffset`**](./offset/struct.FixedOffset.html) specifies
108 //! an arbitrary, fixed time zone such as UTC+09:00 or UTC-10:30.
109 //! This often results from the parsed textual date and time.
110 //! Since it stores the most information and does not depend on the system environment,
111 //! you would want to normalize other `TimeZone`s into this type.
113 //! `DateTime`s with different `TimeZone` types are distinct and do not mix,
114 //! but can be converted to each other using
115 //! the [`DateTime::with_timezone`](./struct.DateTime.html#method.with_timezone) method.
117 //! You can get the current date and time in the UTC time zone
118 //! ([`Utc::now()`](./offset/struct.Utc.html#method.now))
119 //! or in the local time zone
120 //! ([`Local::now()`](./offset/struct.Local.html#method.now)).
123 //! use chrono::prelude::*;
125 //! let utc: DateTime<Utc> = Utc::now(); // e.g. `2014-11-28T12:45:59.324310806Z`
126 //! let local: DateTime<Local> = Local::now(); // e.g. `2014-11-28T21:45:59.324310806+09:00`
127 //! # let _ = utc; let _ = local;
130 //! Alternatively, you can create your own date and time.
131 //! This is a bit verbose due to Rust's lack of function and method overloading,
132 //! but in turn we get a rich combination of initialization methods.
135 //! use chrono::prelude::*;
136 //! use chrono::offset::LocalResult;
138 //! let dt = Utc.ymd(2014, 7, 8).and_hms(9, 10, 11); // `2014-07-08T09:10:11Z`
139 //! // July 8 is 188th day of the year 2014 (`o` for "ordinal")
140 //! assert_eq!(dt, Utc.yo(2014, 189).and_hms(9, 10, 11));
141 //! // July 8 is Tuesday in ISO week 28 of the year 2014.
142 //! assert_eq!(dt, Utc.isoywd(2014, 28, Weekday::Tue).and_hms(9, 10, 11));
144 //! let dt = Utc.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12); // `2014-07-08T09:10:11.012Z`
145 //! assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_micro(9, 10, 11, 12_000));
146 //! assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_nano(9, 10, 11, 12_000_000));
148 //! // dynamic verification
149 //! assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(21, 15, 33),
150 //! LocalResult::Single(Utc.ymd(2014, 7, 8).and_hms(21, 15, 33)));
151 //! assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(80, 15, 33), LocalResult::None);
152 //! assert_eq!(Utc.ymd_opt(2014, 7, 38).and_hms_opt(21, 15, 33), LocalResult::None);
154 //! // other time zone objects can be used to construct a local datetime.
155 //! // obviously, `local_dt` is normally different from `dt`, but `fixed_dt` should be identical.
156 //! let local_dt = Local.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12);
157 //! let fixed_dt = FixedOffset::east(9 * 3600).ymd(2014, 7, 8).and_hms_milli(18, 10, 11, 12);
158 //! assert_eq!(dt, fixed_dt);
159 //! # let _ = local_dt;
162 //! Various properties are available to the date and time, and can be altered individually.
163 //! Most of them are defined in the traits [`Datelike`](./trait.Datelike.html) and
164 //! [`Timelike`](./trait.Timelike.html) which you should `use` before.
165 //! Addition and subtraction is also supported.
166 //! The following illustrates most supported operations to the date and time:
169 //! # extern crate chrono; extern crate time; fn main() {
170 //! use chrono::prelude::*;
171 //! use time::Duration;
173 //! # /* we intentionally fake the datetime...
174 //! // assume this returned `2014-11-28T21:45:59.324310806+09:00`:
175 //! let dt = Local::now();
176 //! # */ // up to here. we now define a fixed datetime for the illustrative purpose.
177 //! # let dt = FixedOffset::east(9*3600).ymd(2014, 11, 28).and_hms_nano(21, 45, 59, 324310806);
179 //! // property accessors
180 //! assert_eq!((dt.year(), dt.month(), dt.day()), (2014, 11, 28));
181 //! assert_eq!((dt.month0(), dt.day0()), (10, 27)); // for unfortunate souls
182 //! assert_eq!((dt.hour(), dt.minute(), dt.second()), (21, 45, 59));
183 //! assert_eq!(dt.weekday(), Weekday::Fri);
184 //! assert_eq!(dt.weekday().number_from_monday(), 5); // Mon=1, ..., Sat=7
185 //! assert_eq!(dt.ordinal(), 332); // the day of year
186 //! assert_eq!(dt.num_days_from_ce(), 735565); // the number of days from and including Jan 1, 1
188 //! // time zone accessor and manipulation
189 //! assert_eq!(dt.offset().fix().local_minus_utc(), 9 * 3600);
190 //! assert_eq!(dt.timezone(), FixedOffset::east(9 * 3600));
191 //! assert_eq!(dt.with_timezone(&Utc), Utc.ymd(2014, 11, 28).and_hms_nano(12, 45, 59, 324310806));
193 //! // a sample of property manipulations (validates dynamically)
194 //! assert_eq!(dt.with_day(29).unwrap().weekday(), Weekday::Sat); // 2014-11-29 is Saturday
195 //! assert_eq!(dt.with_day(32), None);
196 //! assert_eq!(dt.with_year(-300).unwrap().num_days_from_ce(), -109606); // November 29, 301 BCE
198 //! // arithmetic operations
199 //! let dt1 = Utc.ymd(2014, 11, 14).and_hms(8, 9, 10);
200 //! let dt2 = Utc.ymd(2014, 11, 14).and_hms(10, 9, 8);
201 //! assert_eq!(dt1.signed_duration_since(dt2), Duration::seconds(-2 * 3600 + 2));
202 //! assert_eq!(dt2.signed_duration_since(dt1), Duration::seconds(2 * 3600 - 2));
203 //! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) + Duration::seconds(1_000_000_000),
204 //! Utc.ymd(2001, 9, 9).and_hms(1, 46, 40));
205 //! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) - Duration::seconds(1_000_000_000),
206 //! Utc.ymd(1938, 4, 24).and_hms(22, 13, 20));
210 //! Formatting is done via the [`format`](./struct.DateTime.html#method.format) method,
211 //! which format is equivalent to the familiar `strftime` format.
212 //! (See the [`format::strftime` module documentation](./format/strftime/index.html#specifiers)
213 //! for full syntax.)
215 //! The default `to_string` method and `{:?}` specifier also give a reasonable representation.
216 //! Chrono also provides [`to_rfc2822`](./struct.DateTime.html#method.to_rfc2822) and
217 //! [`to_rfc3339`](./struct.DateTime.html#method.to_rfc3339) methods
218 //! for well-known formats.
221 //! use chrono::prelude::*;
223 //! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
224 //! assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2014-11-28 12:00:09");
225 //! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), "Fri Nov 28 12:00:09 2014");
226 //! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), dt.format("%c").to_string());
228 //! assert_eq!(dt.to_string(), "2014-11-28 12:00:09 UTC");
229 //! assert_eq!(dt.to_rfc2822(), "Fri, 28 Nov 2014 12:00:09 +0000");
230 //! assert_eq!(dt.to_rfc3339(), "2014-11-28T12:00:09+00:00");
231 //! assert_eq!(format!("{:?}", dt), "2014-11-28T12:00:09Z");
234 //! Parsing can be done with three methods:
236 //! 1. The standard [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) trait
237 //! (and [`parse`](https://doc.rust-lang.org/std/primitive.str.html#method.parse) method
238 //! on a string) can be used for parsing `DateTime<FixedOffset>`, `DateTime<Utc>` and
239 //! `DateTime<Local>` values. This parses what the `{:?}`
240 //! ([`std::fmt::Debug`](https://doc.rust-lang.org/std/fmt/trait.Debug.html))
241 //! format specifier prints, and requires the offset to be present.
243 //! 2. [`DateTime::parse_from_str`](./struct.DateTime.html#method.parse_from_str) parses
244 //! a date and time with offsets and returns `DateTime<FixedOffset>`.
245 //! This should be used when the offset is a part of input and the caller cannot guess that.
246 //! It *cannot* be used when the offset can be missing.
247 //! [`DateTime::parse_from_rfc2822`](./struct.DateTime.html#method.parse_from_rfc2822)
249 //! [`DateTime::parse_from_rfc3339`](./struct.DateTime.html#method.parse_from_rfc3339)
250 //! are similar but for well-known formats.
252 //! 3. [`Offset::datetime_from_str`](./offset/trait.TimeZone.html#method.datetime_from_str) is
253 //! similar but returns `DateTime` of given offset.
254 //! When the explicit offset is missing from the input, it simply uses given offset.
255 //! It issues an error when the input contains an explicit offset different
256 //! from the current offset.
258 //! More detailed control over the parsing process is available via
259 //! [`format`](./format/index.html) module.
262 //! use chrono::prelude::*;
264 //! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
265 //! let fixed_dt = dt.with_timezone(&FixedOffset::east(9*3600));
268 //! assert_eq!("2014-11-28T12:00:09Z".parse::<DateTime<Utc>>(), Ok(dt.clone()));
269 //! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<Utc>>(), Ok(dt.clone()));
270 //! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<FixedOffset>>(), Ok(fixed_dt.clone()));
273 //! assert_eq!(DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z"),
274 //! Ok(fixed_dt.clone()));
275 //! assert_eq!(DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900"),
276 //! Ok(fixed_dt.clone()));
277 //! assert_eq!(DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00"), Ok(fixed_dt.clone()));
280 //! assert_eq!(Utc.datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S"), Ok(dt.clone()));
281 //! assert_eq!(Utc.datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y"), Ok(dt.clone()));
283 //! // oops, the year is missing!
284 //! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T %Y").is_err());
285 //! // oops, the format string does not include the year at all!
286 //! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T").is_err());
287 //! // oops, the weekday is incorrect!
288 //! assert!(Utc.datetime_from_str("Sat Nov 28 12:00:09 2014", "%a %b %e %T %Y").is_err());
291 //! ### Conversion from and to EPOCH timestamps
293 //! Use [`Utc.timestamp(seconds, nanoseconds)`](./offset/trait.TimeZone.html#method.timestamp)
294 //! to construct a [`DateTime<Utc>`](./struct.DateTime.html) from a UNIX timestamp
295 //! (seconds, nanoseconds that passed since January 1st 1970).
297 //! Use [`DateTime.timestamp`](./struct.DateTime.html#method.timestamp) to get the timestamp (in seconds)
298 //! from a [`DateTime`](./struct.DateTime.html). Additionally, you can use
299 //! [`DateTime.timestamp_subsec_nanos`](./struct.DateTime.html#method.timestamp_subsec_nanos)
300 //! to get the number of additional number of nanoseconds.
303 //! # use chrono::DateTime;
304 //! # use chrono::Utc;
305 //! // We need the trait in scope to use Utc::timestamp().
306 //! use chrono::TimeZone;
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");
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);
317 //! ### Individual date
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.
324 //! use chrono::prelude::*;
325 //! use chrono::offset::LocalResult;
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());
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(),
337 //! There is no timezone-aware `Time` due to the lack of usefulness and also the complexity.
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.
344 //! ### Naive date and time
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.
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.
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.
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.
366 //! Date types are limited in about +/- 262,000 years from the common epoch.
367 //! Time types are limited in the nanosecond accuracy.
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
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`.
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.
384 #![doc(html_root_url = "https://docs.rs/chrono/0.4.0/")]
386 #![cfg_attr(bench, feature(test))] // lib stability features as per RFC #507
387 #![deny(missing_docs)]
388 #![deny(missing_debug_implementations)]
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.
395 // Similarly, redundant_field_names lints on not using the
396 // field-init-shorthand, which was stabilized in rust 1.17.
397 #![cfg_attr(feature = "cargo-clippy", allow(const_static_lifetime, redundant_field_names))]
399 extern crate time
as oldtime
;
400 extern crate num_integer
;
401 extern crate num_traits
;
402 #[cfg(feature = "rustc-serialize")]
403 extern crate rustc_serialize
;
404 #[cfg(feature = "serde")]
405 extern crate serde
as serdelib
;
407 // this reexport is to aid the transition and should not be in the prelude!
408 pub use oldtime
::Duration
;
410 #[doc(no_inline)] pub use offset::{TimeZone, Offset, LocalResult, Utc, FixedOffset, Local};
411 #[doc(no_inline)] pub use naive::{NaiveDate, IsoWeek, NaiveTime, NaiveDateTime};
412 pub use date
::{Date, MIN_DATE, MAX_DATE}
;
413 pub use datetime
::{DateTime, SecondsFormat}
;
414 #[cfg(feature = "rustc-serialize")] pub use datetime::rustc_serialize::TsSeconds;
415 pub use format
::{ParseError, ParseResult}
;
416 pub use round
::SubsecRound
;
418 /// A convenience module appropriate for glob imports (`use chrono::prelude::*;`).
420 #[doc(no_inline)] pub use {Datelike, Timelike, Weekday};
421 #[doc(no_inline)] pub use {TimeZone, Offset};
422 #[doc(no_inline)] pub use {Utc, FixedOffset, Local};
423 #[doc(no_inline)] pub use {NaiveDate, NaiveTime, NaiveDateTime};
424 #[doc(no_inline)] pub use Date;
425 #[doc(no_inline)] pub use {DateTime, SecondsFormat};
426 #[doc(no_inline)] pub use SubsecRound;
429 // useful throughout the codebase
430 macro_rules
! try_opt
{
431 ($e
:expr
) => (match $e { Some(v) => v, None => return None }
)
437 //! Date and time types which do not concern about the timezones.
439 //! They are primarily building blocks for other types
440 //! (e.g. [`TimeZone`](../offset/trait.TimeZone.html)),
441 //! but can be also used for the simpler date and time handling.
449 pub use self::date
::{NaiveDate, MIN_DATE, MAX_DATE}
;
450 pub use self::isoweek
::IsoWeek
;
451 pub use self::time
::NaiveTime
;
452 pub use self::datetime
::NaiveDateTime
;
453 #[cfg(feature = "rustc-serialize")]
454 pub use self::datetime
::rustc_serialize
::TsSeconds
;
457 /// Serialization/Deserialization of naive types in alternate formats
459 /// The various modules in here are intended to be used with serde's [`with`
460 /// annotation][1] to serialize as something other than the default [RFC
463 /// [1]: https://serde.rs/attributes.html#field-attributes
464 /// [2]: https://tools.ietf.org/html/rfc3339
465 #[cfg(feature = "serde")]
467 pub use super::datetime
::serde
::*;
475 /// Serialization/Deserialization in alternate formats
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
481 /// [1]: https://serde.rs/attributes.html#field-attributes
482 /// [2]: https://tools.ietf.org/html/rfc3339
483 #[cfg(feature = "serde")]
485 pub use super::datetime
::serde
::*;
490 /// The order of the days of week depends on the context.
491 /// (This is why this type does *not* implement `PartialOrd` or `Ord` traits.)
492 /// One should prefer `*_from_monday` or `*_from_sunday` methods to get the correct result.
493 #[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
494 #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
513 /// The next day in the week.
515 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
516 /// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
517 /// `w.succ()`: | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun` | `Mon`
519 pub fn succ(&self) -> Weekday
{
521 Weekday
::Mon
=> Weekday
::Tue
,
522 Weekday
::Tue
=> Weekday
::Wed
,
523 Weekday
::Wed
=> Weekday
::Thu
,
524 Weekday
::Thu
=> Weekday
::Fri
,
525 Weekday
::Fri
=> Weekday
::Sat
,
526 Weekday
::Sat
=> Weekday
::Sun
,
527 Weekday
::Sun
=> Weekday
::Mon
,
531 /// The previous day in the week.
533 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
534 /// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
535 /// `w.pred()`: | `Sun` | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat`
537 pub fn pred(&self) -> Weekday
{
539 Weekday
::Mon
=> Weekday
::Sun
,
540 Weekday
::Tue
=> Weekday
::Mon
,
541 Weekday
::Wed
=> Weekday
::Tue
,
542 Weekday
::Thu
=> Weekday
::Wed
,
543 Weekday
::Fri
=> Weekday
::Thu
,
544 Weekday
::Sat
=> Weekday
::Fri
,
545 Weekday
::Sun
=> Weekday
::Sat
,
549 /// Returns a day-of-week number starting from Monday = 1. (ISO 8601 weekday number)
551 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
552 /// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
553 /// `w.number_from_monday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 7
555 pub fn number_from_monday(&self) -> u32 {
567 /// Returns a day-of-week number starting from Sunday = 1.
569 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
570 /// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
571 /// `w.number_from_sunday()`: | 2 | 3 | 4 | 5 | 6 | 7 | 1
573 pub fn number_from_sunday(&self) -> u32 {
585 /// Returns a day-of-week number starting from Monday = 0.
587 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
588 /// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
589 /// `w.num_days_from_monday()`: | 0 | 1 | 2 | 3 | 4 | 5 | 6
591 pub fn num_days_from_monday(&self) -> u32 {
603 /// Returns a day-of-week number starting from Sunday = 0.
605 /// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
606 /// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
607 /// `w.num_days_from_sunday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 0
609 pub fn num_days_from_sunday(&self) -> u32 {
622 /// Any weekday can be represented as an integer from 0 to 6, which equals to
623 /// [`Weekday::num_days_from_monday`](#method.num_days_from_monday) in this implementation.
624 /// Do not heavily depend on this though; use explicit methods whenever possible.
625 impl num_traits
::FromPrimitive
for Weekday
{
627 fn from_i64(n
: i64) -> Option
<Weekday
> {
629 0 => Some(Weekday
::Mon
),
630 1 => Some(Weekday
::Tue
),
631 2 => Some(Weekday
::Wed
),
632 3 => Some(Weekday
::Thu
),
633 4 => Some(Weekday
::Fri
),
634 5 => Some(Weekday
::Sat
),
635 6 => Some(Weekday
::Sun
),
641 fn from_u64(n
: u64) -> Option
<Weekday
> {
643 0 => Some(Weekday
::Mon
),
644 1 => Some(Weekday
::Tue
),
645 2 => Some(Weekday
::Wed
),
646 3 => Some(Weekday
::Thu
),
647 4 => Some(Weekday
::Fri
),
648 5 => Some(Weekday
::Sat
),
649 6 => Some(Weekday
::Sun
),
657 /// An error resulting from reading `Weekday` value with `FromStr`.
658 #[derive(Clone, PartialEq)]
659 pub struct ParseWeekdayError
{
663 impl fmt
::Debug
for ParseWeekdayError
{
664 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
665 write
!(f
, "ParseWeekdayError {{ .. }}")
669 // the actual `FromStr` implementation is in the `format` module to leverage the existing code
671 #[cfg(feature = "serde")]
675 use serdelib
::{ser, de}
;
677 impl ser
::Serialize
for Weekday
{
678 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
679 where S
: ser
::Serializer
681 serializer
.serialize_str(&format
!("{:?}", self))
685 struct WeekdayVisitor
;
687 impl<'de
> de
::Visitor
<'de
> for WeekdayVisitor
{
688 type Value
= Weekday
;
690 fn expecting(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
694 fn visit_str
<E
>(self, value
: &str) -> Result
<Self::Value
, E
>
697 value
.parse().map_err(|_
| E
::custom("short or long weekday names expected"))
701 impl<'de
> de
::Deserialize
<'de
> for Weekday
{
702 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
703 where D
: de
::Deserializer
<'de
>
705 deserializer
.deserialize_str(WeekdayVisitor
)
710 extern crate serde_json
;
713 fn test_serde_serialize() {
714 use self::serde_json
::to_string
;
717 let cases
: Vec
<(Weekday
, &str)> = vec
![
727 for (weekday
, expected_str
) in cases
{
728 let string
= to_string(&weekday
).unwrap();
729 assert_eq
!(string
, expected_str
);
734 fn test_serde_deserialize() {
735 use self::serde_json
::from_str
;
738 let cases
: Vec
<(&str, Weekday
)> = vec
![
744 ("\"tuesday\"", Tue
),
746 ("\"wednesday\"", Wed
),
748 ("\"thursday\"", Thu
),
752 ("\"saturday\"", Sat
),
757 for (str, expected_weekday
) in cases
{
758 let weekday
= from_str
::<Weekday
>(str).unwrap();
759 assert_eq
!(weekday
, expected_weekday
);
762 let errors
: Vec
<&str> = vec
![
772 from_str
::<Weekday
>(str).unwrap_err();
777 /// The common set of methods for date component.
778 pub trait Datelike
: Sized
{
779 /// Returns the year number in the [calendar date](./naive/struct.NaiveDate.html#calendar-date).
780 fn year(&self) -> i32;
782 /// Returns the absolute year number starting from 1 with a boolean flag,
783 /// which is false when the year predates the epoch (BCE/BC) and true otherwise (CE/AD).
785 fn year_ce(&self) -> (bool
, u32) {
786 let year
= self.year();
788 (false, (1 - year
) as u32)
794 /// Returns the month number starting from 1.
796 /// The return value ranges from 1 to 12.
797 fn month(&self) -> u32;
799 /// Returns the month number starting from 0.
801 /// The return value ranges from 0 to 11.
802 fn month0(&self) -> u32;
804 /// Returns the day of month starting from 1.
806 /// The return value ranges from 1 to 31. (The last day of month differs by months.)
807 fn day(&self) -> u32;
809 /// Returns the day of month starting from 0.
811 /// The return value ranges from 0 to 30. (The last day of month differs by months.)
812 fn day0(&self) -> u32;
814 /// Returns the day of year starting from 1.
816 /// The return value ranges from 1 to 366. (The last day of year differs by years.)
817 fn ordinal(&self) -> u32;
819 /// Returns the day of year starting from 0.
821 /// The return value ranges from 0 to 365. (The last day of year differs by years.)
822 fn ordinal0(&self) -> u32;
824 /// Returns the day of week.
825 fn weekday(&self) -> Weekday
;
827 /// Returns the ISO week.
828 fn iso_week(&self) -> IsoWeek
;
830 /// Makes a new value with the year number changed.
832 /// Returns `None` when the resulting value would be invalid.
833 fn with_year(&self, year
: i32) -> Option
<Self>;
835 /// Makes a new value with the month number (starting from 1) changed.
837 /// Returns `None` when the resulting value would be invalid.
838 fn with_month(&self, month
: u32) -> Option
<Self>;
840 /// Makes a new value with the month number (starting from 0) changed.
842 /// Returns `None` when the resulting value would be invalid.
843 fn with_month0(&self, month0
: u32) -> Option
<Self>;
845 /// Makes a new value with the day of month (starting from 1) changed.
847 /// Returns `None` when the resulting value would be invalid.
848 fn with_day(&self, day
: u32) -> Option
<Self>;
850 /// Makes a new value with the day of month (starting from 0) changed.
852 /// Returns `None` when the resulting value would be invalid.
853 fn with_day0(&self, day0
: u32) -> Option
<Self>;
855 /// Makes a new value with the day of year (starting from 1) changed.
857 /// Returns `None` when the resulting value would be invalid.
858 fn with_ordinal(&self, ordinal
: u32) -> Option
<Self>;
860 /// Makes a new value with the day of year (starting from 0) changed.
862 /// Returns `None` when the resulting value would be invalid.
863 fn with_ordinal0(&self, ordinal0
: u32) -> Option
<Self>;
865 /// Returns the number of days since January 1, 1 (Day 1) in the proleptic Gregorian calendar.
866 fn num_days_from_ce(&self) -> i32 {
867 // we know this wouldn't overflow since year is limited to 1/2^13 of i32's full range.
868 let mut year
= self.year() - 1;
871 let excess
= 1 + (-year
) / 400;
872 year
+= excess
* 400;
873 ndays
-= excess
* 146_097;
875 let div_100
= year
/ 100;
876 ndays
+= ((year
* 1461) >> 2) - div_100
+ (div_100
>> 2);
877 ndays
+ self.ordinal() as i32
881 /// The common set of methods for time component.
882 pub trait Timelike
: Sized
{
883 /// Returns the hour number from 0 to 23.
884 fn hour(&self) -> u32;
886 /// Returns the hour number from 1 to 12 with a boolean flag,
887 /// which is false for AM and true for PM.
889 fn hour12(&self) -> (bool
, u32) {
890 let hour
= self.hour();
891 let mut hour12
= hour
% 12;
898 /// Returns the minute number from 0 to 59.
899 fn minute(&self) -> u32;
901 /// Returns the second number from 0 to 59.
902 fn second(&self) -> u32;
904 /// Returns the number of nanoseconds since the whole non-leap second.
905 /// The range from 1,000,000,000 to 1,999,999,999 represents
906 /// the [leap second](./naive/struct.NaiveTime.html#leap-second-handling).
907 fn nanosecond(&self) -> u32;
909 /// Makes a new value with the hour number changed.
911 /// Returns `None` when the resulting value would be invalid.
912 fn with_hour(&self, hour
: u32) -> Option
<Self>;
914 /// Makes a new value with the minute number changed.
916 /// Returns `None` when the resulting value would be invalid.
917 fn with_minute(&self, min
: u32) -> Option
<Self>;
919 /// Makes a new value with the second number changed.
921 /// Returns `None` when the resulting value would be invalid.
922 /// As with the [`second`](#tymethod.second) method,
923 /// the input range is restricted to 0 through 59.
924 fn with_second(&self, sec
: u32) -> Option
<Self>;
926 /// Makes a new value with nanoseconds since the whole non-leap second changed.
928 /// Returns `None` when the resulting value would be invalid.
929 /// As with the [`nanosecond`](#tymethod.nanosecond) method,
930 /// the input range can exceed 1,000,000,000 for leap seconds.
931 fn with_nanosecond(&self, nano
: u32) -> Option
<Self>;
933 /// Returns the number of non-leap seconds past the last midnight.
935 fn num_seconds_from_midnight(&self) -> u32 {
936 self.hour() * 3600 + self.minute() * 60 + self.second()
940 #[cfg(test)] extern crate num_iter;
943 fn test_readme_doomsday() {
944 use num_iter
::range_inclusive
;
946 for y
in range_inclusive(naive
::MIN_DATE
.year(), naive
::MAX_DATE
.year()) {
948 let d4
= NaiveDate
::from_ymd(y
, 4, 4);
949 let d6
= NaiveDate
::from_ymd(y
, 6, 6);
950 let d8
= NaiveDate
::from_ymd(y
, 8, 8);
951 let d10
= NaiveDate
::from_ymd(y
, 10, 10);
952 let d12
= NaiveDate
::from_ymd(y
, 12, 12);
954 // nine to five, seven-eleven
955 let d59
= NaiveDate
::from_ymd(y
, 5, 9);
956 let d95
= NaiveDate
::from_ymd(y
, 9, 5);
957 let d711
= NaiveDate
::from_ymd(y
, 7, 11);
958 let d117
= NaiveDate
::from_ymd(y
, 11, 7);
961 let d30
= NaiveDate
::from_ymd(y
, 3, 1).pred();
963 let weekday
= d30
.weekday();
964 let other_dates
= [d4
, d6
, d8
, d10
, d12
, d59
, d95
, d711
, d117
];
965 assert
!(other_dates
.iter().all(|d
| d
.weekday() == weekday
));