#![doc(html_root_url = "https://docs.rs/chrono/latest/")]
#![cfg_attr(feature = "bench", feature(test))] #![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(dead_code)]
#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![cfg_attr(feature = "cargo-clippy", allow(
const_static_lifetime,
redundant_field_names,
trivially_copy_pass_by_ref,
))]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(any(feature = "std", test))]
extern crate std as core;
#[cfg(all(feature = "std", not(feature="alloc")))]
extern crate std as alloc;
#[cfg(feature="clock")]
extern crate time as oldtime;
extern crate num_integer;
extern crate num_traits;
#[cfg(feature = "rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature = "serde")]
extern crate serde as serdelib;
#[cfg(test)]
#[macro_use]
extern crate doc_comment;
#[cfg(all(target_arch = "wasm32", feature="wasmbind"))]
extern crate wasm_bindgen;
#[cfg(all(target_arch = "wasm32", feature="wasmbind"))]
extern crate js_sys;
#[cfg(feature = "bench")]
extern crate test;
#[cfg(test)]
doctest!("../README.md");
pub use oldtime::Duration;
#[cfg(feature="clock")]
#[doc(no_inline)] pub use offset::Local;
#[doc(no_inline)] pub use offset::{TimeZone, Offset, LocalResult, Utc, FixedOffset};
#[doc(no_inline)] pub use naive::{NaiveDate, IsoWeek, NaiveTime, NaiveDateTime};
pub use date::{Date, MIN_DATE, MAX_DATE};
pub use datetime::{DateTime, SecondsFormat};
#[cfg(feature = "rustc-serialize")]
pub use datetime::rustc_serialize::TsSeconds;
pub use format::{ParseError, ParseResult};
pub use round::SubsecRound;
pub mod prelude {
#[doc(no_inline)] pub use {Datelike, Timelike, Weekday};
#[doc(no_inline)] pub use {TimeZone, Offset};
#[cfg(feature="clock")]
#[doc(no_inline)] pub use Local;
#[doc(no_inline)] pub use {Utc, FixedOffset};
#[doc(no_inline)] pub use {NaiveDate, NaiveTime, NaiveDateTime};
#[doc(no_inline)] pub use Date;
#[doc(no_inline)] pub use {DateTime, SecondsFormat};
#[doc(no_inline)] pub use SubsecRound;
}
macro_rules! try_opt {
($e:expr) => (match $e { Some(v) => v, None => return None })
}
mod div;
#[cfg(not(feature="clock"))]
mod oldtime;
pub mod offset;
pub mod naive {
mod internals;
mod date;
mod isoweek;
mod time;
mod datetime;
pub use self::date::{NaiveDate, MIN_DATE, MAX_DATE};
pub use self::isoweek::IsoWeek;
pub use self::time::NaiveTime;
pub use self::datetime::NaiveDateTime;
#[cfg(feature = "rustc-serialize")]
#[allow(deprecated)]
pub use self::datetime::rustc_serialize::TsSeconds;
#[cfg(feature = "serde")]
pub mod serde {
pub use super::datetime::serde::*;
}
}
mod date;
mod datetime;
pub mod format;
mod round;
#[cfg(feature = "serde")]
pub mod serde {
pub use super::datetime::serde::*;
}
#[cfg(feature = "serde")]
enum SerdeError<V: fmt::Display, D: fmt::Display> {
NonExistent { timestamp: V },
Ambiguous { timestamp: V, min: D, max: D },
}
#[cfg(feature = "serde")]
fn ne_timestamp<T: fmt::Display>(ts: T) -> SerdeError<T, u8> {
SerdeError::NonExistent::<T, u8> { timestamp: ts }
}
#[cfg(feature = "serde")]
impl<V: fmt::Display, D: fmt::Display> fmt::Debug for SerdeError<V, D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ChronoSerdeError({})", self)
}
}
#[cfg(feature = "serde")]
impl<V: fmt::Display, D: fmt::Display> fmt::Display for SerdeError<V, D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&SerdeError::NonExistent { ref timestamp } => write!(
f, "value is not a legal timestamp: {}", timestamp),
&SerdeError::Ambiguous { ref timestamp, ref min, ref max } => write!(
f, "value is an ambiguous timestamp: {}, could be either of {}, {}",
timestamp, min, max),
}
}
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub enum Weekday {
Mon = 0,
Tue = 1,
Wed = 2,
Thu = 3,
Fri = 4,
Sat = 5,
Sun = 6,
}
impl Weekday {
#[inline]
pub fn succ(&self) -> Weekday {
match *self {
Weekday::Mon => Weekday::Tue,
Weekday::Tue => Weekday::Wed,
Weekday::Wed => Weekday::Thu,
Weekday::Thu => Weekday::Fri,
Weekday::Fri => Weekday::Sat,
Weekday::Sat => Weekday::Sun,
Weekday::Sun => Weekday::Mon,
}
}
#[inline]
pub fn pred(&self) -> Weekday {
match *self {
Weekday::Mon => Weekday::Sun,
Weekday::Tue => Weekday::Mon,
Weekday::Wed => Weekday::Tue,
Weekday::Thu => Weekday::Wed,
Weekday::Fri => Weekday::Thu,
Weekday::Sat => Weekday::Fri,
Weekday::Sun => Weekday::Sat,
}
}
#[inline]
pub fn number_from_monday(&self) -> u32 {
match *self {
Weekday::Mon => 1,
Weekday::Tue => 2,
Weekday::Wed => 3,
Weekday::Thu => 4,
Weekday::Fri => 5,
Weekday::Sat => 6,
Weekday::Sun => 7,
}
}
#[inline]
pub fn number_from_sunday(&self) -> u32 {
match *self {
Weekday::Mon => 2,
Weekday::Tue => 3,
Weekday::Wed => 4,
Weekday::Thu => 5,
Weekday::Fri => 6,
Weekday::Sat => 7,
Weekday::Sun => 1,
}
}
#[inline]
pub fn num_days_from_monday(&self) -> u32 {
match *self {
Weekday::Mon => 0,
Weekday::Tue => 1,
Weekday::Wed => 2,
Weekday::Thu => 3,
Weekday::Fri => 4,
Weekday::Sat => 5,
Weekday::Sun => 6,
}
}
#[inline]
pub fn num_days_from_sunday(&self) -> u32 {
match *self {
Weekday::Mon => 1,
Weekday::Tue => 2,
Weekday::Wed => 3,
Weekday::Thu => 4,
Weekday::Fri => 5,
Weekday::Sat => 6,
Weekday::Sun => 0,
}
}
}
impl fmt::Display for Weekday {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match *self {
Weekday::Mon => "Mon",
Weekday::Tue => "Tue",
Weekday::Wed => "Wed",
Weekday::Thu => "Thu",
Weekday::Fri => "Fri",
Weekday::Sat => "Sat",
Weekday::Sun => "Sun",
})
}
}
impl num_traits::FromPrimitive for Weekday {
#[inline]
fn from_i64(n: i64) -> Option<Weekday> {
match n {
0 => Some(Weekday::Mon),
1 => Some(Weekday::Tue),
2 => Some(Weekday::Wed),
3 => Some(Weekday::Thu),
4 => Some(Weekday::Fri),
5 => Some(Weekday::Sat),
6 => Some(Weekday::Sun),
_ => None,
}
}
#[inline]
fn from_u64(n: u64) -> Option<Weekday> {
match n {
0 => Some(Weekday::Mon),
1 => Some(Weekday::Tue),
2 => Some(Weekday::Wed),
3 => Some(Weekday::Thu),
4 => Some(Weekday::Fri),
5 => Some(Weekday::Sat),
6 => Some(Weekday::Sun),
_ => None,
}
}
}
use core::fmt;
#[derive(Clone, PartialEq)]
pub struct ParseWeekdayError {
_dummy: (),
}
impl fmt::Debug for ParseWeekdayError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ParseWeekdayError {{ .. }}")
}
}
#[cfg(feature = "serde")]
mod weekday_serde {
use super::Weekday;
use core::fmt;
use serdelib::{ser, de};
impl ser::Serialize for Weekday {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer
{
serializer.collect_str(&self)
}
}
struct WeekdayVisitor;
impl<'de> de::Visitor<'de> for WeekdayVisitor {
type Value = Weekday;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Weekday")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where E: de::Error
{
value.parse().map_err(|_| E::custom("short or long weekday names expected"))
}
}
impl<'de> de::Deserialize<'de> for Weekday {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: de::Deserializer<'de>
{
deserializer.deserialize_str(WeekdayVisitor)
}
}
#[cfg(test)]
extern crate serde_json;
#[test]
fn test_serde_serialize() {
use self::serde_json::to_string;
use Weekday::*;
let cases: Vec<(Weekday, &str)> = vec![
(Mon, "\"Mon\""),
(Tue, "\"Tue\""),
(Wed, "\"Wed\""),
(Thu, "\"Thu\""),
(Fri, "\"Fri\""),
(Sat, "\"Sat\""),
(Sun, "\"Sun\""),
];
for (weekday, expected_str) in cases {
let string = to_string(&weekday).unwrap();
assert_eq!(string, expected_str);
}
}
#[test]
fn test_serde_deserialize() {
use self::serde_json::from_str;
use Weekday::*;
let cases: Vec<(&str, Weekday)> = vec![
("\"mon\"", Mon),
("\"MONDAY\"", Mon),
("\"MonDay\"", Mon),
("\"mOn\"", Mon),
("\"tue\"", Tue),
("\"tuesday\"", Tue),
("\"wed\"", Wed),
("\"wednesday\"", Wed),
("\"thu\"", Thu),
("\"thursday\"", Thu),
("\"fri\"", Fri),
("\"friday\"", Fri),
("\"sat\"", Sat),
("\"saturday\"", Sat),
("\"sun\"", Sun),
("\"sunday\"", Sun),
];
for (str, expected_weekday) in cases {
let weekday = from_str::<Weekday>(str).unwrap();
assert_eq!(weekday, expected_weekday);
}
let errors: Vec<&str> = vec![
"\"not a weekday\"",
"\"monDAYs\"",
"\"mond\"",
"mon",
"\"thur\"",
"\"thurs\"",
];
for str in errors {
from_str::<Weekday>(str).unwrap_err();
}
}
}
pub trait Datelike: Sized {
fn year(&self) -> i32;
#[inline]
fn year_ce(&self) -> (bool, u32) {
let year = self.year();
if year < 1 {
(false, (1 - year) as u32)
} else {
(true, year as u32)
}
}
fn month(&self) -> u32;
fn month0(&self) -> u32;
fn day(&self) -> u32;
fn day0(&self) -> u32;
fn ordinal(&self) -> u32;
fn ordinal0(&self) -> u32;
fn weekday(&self) -> Weekday;
fn iso_week(&self) -> IsoWeek;
fn with_year(&self, year: i32) -> Option<Self>;
fn with_month(&self, month: u32) -> Option<Self>;
fn with_month0(&self, month0: u32) -> Option<Self>;
fn with_day(&self, day: u32) -> Option<Self>;
fn with_day0(&self, day0: u32) -> Option<Self>;
fn with_ordinal(&self, ordinal: u32) -> Option<Self>;
fn with_ordinal0(&self, ordinal0: u32) -> Option<Self>;
fn num_days_from_ce(&self) -> i32 {
let mut year = self.year() - 1;
let mut ndays = 0;
if year < 0 {
let excess = 1 + (-year) / 400;
year += excess * 400;
ndays -= excess * 146_097;
}
let div_100 = year / 100;
ndays += ((year * 1461) >> 2) - div_100 + (div_100 >> 2);
ndays + self.ordinal() as i32
}
}
pub trait Timelike: Sized {
fn hour(&self) -> u32;
#[inline]
fn hour12(&self) -> (bool, u32) {
let hour = self.hour();
let mut hour12 = hour % 12;
if hour12 == 0 {
hour12 = 12;
}
(hour >= 12, hour12)
}
fn minute(&self) -> u32;
fn second(&self) -> u32;
fn nanosecond(&self) -> u32;
fn with_hour(&self, hour: u32) -> Option<Self>;
fn with_minute(&self, min: u32) -> Option<Self>;
fn with_second(&self, sec: u32) -> Option<Self>;
fn with_nanosecond(&self, nano: u32) -> Option<Self>;
#[inline]
fn num_seconds_from_midnight(&self) -> u32 {
self.hour() * 3600 + self.minute() * 60 + self.second()
}
}
#[cfg(test)] extern crate num_iter;
#[test]
fn test_readme_doomsday() {
use num_iter::range_inclusive;
for y in range_inclusive(naive::MIN_DATE.year(), naive::MAX_DATE.year()) {
let d4 = NaiveDate::from_ymd(y, 4, 4);
let d6 = NaiveDate::from_ymd(y, 6, 6);
let d8 = NaiveDate::from_ymd(y, 8, 8);
let d10 = NaiveDate::from_ymd(y, 10, 10);
let d12 = NaiveDate::from_ymd(y, 12, 12);
let d59 = NaiveDate::from_ymd(y, 5, 9);
let d95 = NaiveDate::from_ymd(y, 9, 5);
let d711 = NaiveDate::from_ymd(y, 7, 11);
let d117 = NaiveDate::from_ymd(y, 11, 7);
let d30 = NaiveDate::from_ymd(y, 3, 1).pred();
let weekday = d30.weekday();
let other_dates = [d4, d6, d8, d10, d12, d59, d95, d711, d117];
assert!(other_dates.iter().all(|d| d.weekday() == weekday));
}
}