#[cfg(any(feature = "alloc", feature = "std", test))]
use core::borrow::Borrow;
use core::ops::{Add, AddAssign, Sub, SubAssign};
use core::{fmt, str};
use num_integer::div_mod_floor;
use num_traits::ToPrimitive;
#[cfg(feature = "rkyv")]
use rkyv::{Archive, Deserialize, Serialize};
#[cfg(any(feature = "alloc", feature = "std", test))]
use crate::format::DelayedFormat;
use crate::format::{parse, ParseError, ParseResult, Parsed, StrftimeItems};
use crate::format::{Fixed, Item, Numeric, Pad};
use crate::naive::{IsoWeek, NaiveDate, NaiveTime};
use crate::oldtime::Duration as OldDuration;
use crate::{DateTime, Datelike, LocalResult, TimeZone, Timelike, Weekday};
#[cfg(feature = "rustc-serialize")]
pub(super) mod rustc_serialize;
#[cfg(feature = "serde")]
pub(crate) mod serde;
#[cfg(test)]
mod tests;
const MAX_SECS_BITS: usize = 44;
#[deprecated(since = "0.4.20", note = "Use NaiveDateTime::MIN instead")]
pub const MIN_DATETIME: NaiveDateTime = NaiveDateTime::MIN;
#[deprecated(since = "0.4.20", note = "Use NaiveDateTime::MAX instead")]
pub const MAX_DATETIME: NaiveDateTime = NaiveDateTime::MAX;
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Copy, Clone)]
#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
pub struct NaiveDateTime {
date: NaiveDate,
time: NaiveTime,
}
impl NaiveDateTime {
#[inline]
pub fn new(date: NaiveDate, time: NaiveTime) -> NaiveDateTime {
NaiveDateTime { date, time }
}
#[inline]
pub fn from_timestamp(secs: i64, nsecs: u32) -> NaiveDateTime {
let datetime = NaiveDateTime::from_timestamp_opt(secs, nsecs);
datetime.expect("invalid or out-of-range datetime")
}
#[inline]
pub fn from_timestamp_opt(secs: i64, nsecs: u32) -> Option<NaiveDateTime> {
let (days, secs) = div_mod_floor(secs, 86_400);
let date = days
.to_i32()
.and_then(|days| days.checked_add(719_163))
.and_then(NaiveDate::from_num_days_from_ce_opt);
let time = NaiveTime::from_num_seconds_from_midnight_opt(secs as u32, nsecs);
match (date, time) {
(Some(date), Some(time)) => Some(NaiveDateTime { date, time }),
(_, _) => None,
}
}
pub fn parse_from_str(s: &str, fmt: &str) -> ParseResult<NaiveDateTime> {
let mut parsed = Parsed::new();
parse(&mut parsed, s, StrftimeItems::new(fmt))?;
parsed.to_naive_datetime_with_offset(0) }
#[inline]
pub fn date(&self) -> NaiveDate {
self.date
}
#[inline]
pub fn time(&self) -> NaiveTime {
self.time
}
#[inline]
pub fn timestamp(&self) -> i64 {
const UNIX_EPOCH_DAY: i64 = 719_163;
let gregorian_day = i64::from(self.date.num_days_from_ce());
let seconds_from_midnight = i64::from(self.time.num_seconds_from_midnight());
(gregorian_day - UNIX_EPOCH_DAY) * 86_400 + seconds_from_midnight
}
#[inline]
pub fn timestamp_millis(&self) -> i64 {
let as_ms = self.timestamp() * 1000;
as_ms + i64::from(self.timestamp_subsec_millis())
}
#[inline]
pub fn timestamp_micros(&self) -> i64 {
let as_us = self.timestamp() * 1_000_000;
as_us + i64::from(self.timestamp_subsec_micros())
}
#[inline]
pub fn timestamp_nanos(&self) -> i64 {
let as_ns = self.timestamp() * 1_000_000_000;
as_ns + i64::from(self.timestamp_subsec_nanos())
}
#[inline]
pub fn timestamp_subsec_millis(&self) -> u32 {
self.timestamp_subsec_nanos() / 1_000_000
}
#[inline]
pub fn timestamp_subsec_micros(&self) -> u32 {
self.timestamp_subsec_nanos() / 1_000
}
#[inline]
pub fn timestamp_subsec_nanos(&self) -> u32 {
self.time.nanosecond()
}
pub fn checked_add_signed(self, rhs: OldDuration) -> Option<NaiveDateTime> {
let (time, rhs) = self.time.overflowing_add_signed(rhs);
if rhs <= (-1 << MAX_SECS_BITS) || rhs >= (1 << MAX_SECS_BITS) {
return None;
}
let date = self.date.checked_add_signed(OldDuration::seconds(rhs))?;
Some(NaiveDateTime { date, time })
}
pub fn checked_sub_signed(self, rhs: OldDuration) -> Option<NaiveDateTime> {
let (time, rhs) = self.time.overflowing_sub_signed(rhs);
if rhs <= (-1 << MAX_SECS_BITS) || rhs >= (1 << MAX_SECS_BITS) {
return None;
}
let date = self.date.checked_sub_signed(OldDuration::seconds(rhs))?;
Some(NaiveDateTime { date, time })
}
pub fn signed_duration_since(self, rhs: NaiveDateTime) -> OldDuration {
self.date.signed_duration_since(rhs.date) + self.time.signed_duration_since(rhs.time)
}
#[cfg(any(feature = "alloc", feature = "std", test))]
#[inline]
pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
where
I: Iterator<Item = B> + Clone,
B: Borrow<Item<'a>>,
{
DelayedFormat::new(Some(self.date), Some(self.time), items)
}
#[cfg(any(feature = "alloc", feature = "std", test))]
#[inline]
pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
self.format_with_items(StrftimeItems::new(fmt))
}
pub fn and_local_timezone<Tz: TimeZone>(&self, tz: Tz) -> LocalResult<DateTime<Tz>> {
tz.from_local_datetime(self)
}
pub const MIN: Self = Self { date: NaiveDate::MIN, time: NaiveTime::MIN };
pub const MAX: Self = Self { date: NaiveDate::MAX, time: NaiveTime::MAX };
}
impl Datelike for NaiveDateTime {
#[inline]
fn year(&self) -> i32 {
self.date.year()
}
#[inline]
fn month(&self) -> u32 {
self.date.month()
}
#[inline]
fn month0(&self) -> u32 {
self.date.month0()
}
#[inline]
fn day(&self) -> u32 {
self.date.day()
}
#[inline]
fn day0(&self) -> u32 {
self.date.day0()
}
#[inline]
fn ordinal(&self) -> u32 {
self.date.ordinal()
}
#[inline]
fn ordinal0(&self) -> u32 {
self.date.ordinal0()
}
#[inline]
fn weekday(&self) -> Weekday {
self.date.weekday()
}
#[inline]
fn iso_week(&self) -> IsoWeek {
self.date.iso_week()
}
#[inline]
fn with_year(&self, year: i32) -> Option<NaiveDateTime> {
self.date.with_year(year).map(|d| NaiveDateTime { date: d, ..*self })
}
#[inline]
fn with_month(&self, month: u32) -> Option<NaiveDateTime> {
self.date.with_month(month).map(|d| NaiveDateTime { date: d, ..*self })
}
#[inline]
fn with_month0(&self, month0: u32) -> Option<NaiveDateTime> {
self.date.with_month0(month0).map(|d| NaiveDateTime { date: d, ..*self })
}
#[inline]
fn with_day(&self, day: u32) -> Option<NaiveDateTime> {
self.date.with_day(day).map(|d| NaiveDateTime { date: d, ..*self })
}
#[inline]
fn with_day0(&self, day0: u32) -> Option<NaiveDateTime> {
self.date.with_day0(day0).map(|d| NaiveDateTime { date: d, ..*self })
}
#[inline]
fn with_ordinal(&self, ordinal: u32) -> Option<NaiveDateTime> {
self.date.with_ordinal(ordinal).map(|d| NaiveDateTime { date: d, ..*self })
}
#[inline]
fn with_ordinal0(&self, ordinal0: u32) -> Option<NaiveDateTime> {
self.date.with_ordinal0(ordinal0).map(|d| NaiveDateTime { date: d, ..*self })
}
}
impl Timelike for NaiveDateTime {
#[inline]
fn hour(&self) -> u32 {
self.time.hour()
}
#[inline]
fn minute(&self) -> u32 {
self.time.minute()
}
#[inline]
fn second(&self) -> u32 {
self.time.second()
}
#[inline]
fn nanosecond(&self) -> u32 {
self.time.nanosecond()
}
#[inline]
fn with_hour(&self, hour: u32) -> Option<NaiveDateTime> {
self.time.with_hour(hour).map(|t| NaiveDateTime { time: t, ..*self })
}
#[inline]
fn with_minute(&self, min: u32) -> Option<NaiveDateTime> {
self.time.with_minute(min).map(|t| NaiveDateTime { time: t, ..*self })
}
#[inline]
fn with_second(&self, sec: u32) -> Option<NaiveDateTime> {
self.time.with_second(sec).map(|t| NaiveDateTime { time: t, ..*self })
}
#[inline]
fn with_nanosecond(&self, nano: u32) -> Option<NaiveDateTime> {
self.time.with_nanosecond(nano).map(|t| NaiveDateTime { time: t, ..*self })
}
}
impl Add<OldDuration> for NaiveDateTime {
type Output = NaiveDateTime;
#[inline]
fn add(self, rhs: OldDuration) -> NaiveDateTime {
self.checked_add_signed(rhs).expect("`NaiveDateTime + Duration` overflowed")
}
}
impl AddAssign<OldDuration> for NaiveDateTime {
#[inline]
fn add_assign(&mut self, rhs: OldDuration) {
*self = self.add(rhs);
}
}
impl Sub<OldDuration> for NaiveDateTime {
type Output = NaiveDateTime;
#[inline]
fn sub(self, rhs: OldDuration) -> NaiveDateTime {
self.checked_sub_signed(rhs).expect("`NaiveDateTime - Duration` overflowed")
}
}
impl SubAssign<OldDuration> for NaiveDateTime {
#[inline]
fn sub_assign(&mut self, rhs: OldDuration) {
*self = self.sub(rhs);
}
}
impl Sub<NaiveDateTime> for NaiveDateTime {
type Output = OldDuration;
#[inline]
fn sub(self, rhs: NaiveDateTime) -> OldDuration {
self.signed_duration_since(rhs)
}
}
impl fmt::Debug for NaiveDateTime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}T{:?}", self.date, self.time)
}
}
impl fmt::Display for NaiveDateTime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.date, self.time)
}
}
impl str::FromStr for NaiveDateTime {
type Err = ParseError;
fn from_str(s: &str) -> ParseResult<NaiveDateTime> {
const ITEMS: &[Item<'static>] = &[
Item::Numeric(Numeric::Year, Pad::Zero),
Item::Space(""),
Item::Literal("-"),
Item::Numeric(Numeric::Month, Pad::Zero),
Item::Space(""),
Item::Literal("-"),
Item::Numeric(Numeric::Day, Pad::Zero),
Item::Space(""),
Item::Literal("T"), Item::Numeric(Numeric::Hour, Pad::Zero),
Item::Space(""),
Item::Literal(":"),
Item::Numeric(Numeric::Minute, Pad::Zero),
Item::Space(""),
Item::Literal(":"),
Item::Numeric(Numeric::Second, Pad::Zero),
Item::Fixed(Fixed::Nanosecond),
Item::Space(""),
];
let mut parsed = Parsed::new();
parse(&mut parsed, s, ITEMS.iter())?;
parsed.to_naive_datetime_with_offset(0)
}
}
impl Default for NaiveDateTime {
fn default() -> Self {
NaiveDateTime::from_timestamp(0, 0)
}
}
#[cfg(all(test, any(feature = "rustc-serialize", feature = "serde")))]
fn test_encodable_json<F, E>(to_string: F)
where
F: Fn(&NaiveDateTime) -> Result<String, E>,
E: ::std::fmt::Debug,
{
assert_eq!(
to_string(&NaiveDate::from_ymd(2016, 7, 8).and_hms_milli(9, 10, 48, 90)).ok(),
Some(r#""2016-07-08T09:10:48.090""#.into())
);
assert_eq!(
to_string(&NaiveDate::from_ymd(2014, 7, 24).and_hms(12, 34, 6)).ok(),
Some(r#""2014-07-24T12:34:06""#.into())
);
assert_eq!(
to_string(&NaiveDate::from_ymd(0, 1, 1).and_hms_milli(0, 0, 59, 1_000)).ok(),
Some(r#""0000-01-01T00:00:60""#.into())
);
assert_eq!(
to_string(&NaiveDate::from_ymd(-1, 12, 31).and_hms_nano(23, 59, 59, 7)).ok(),
Some(r#""-0001-12-31T23:59:59.000000007""#.into())
);
assert_eq!(
to_string(&NaiveDate::MIN.and_hms(0, 0, 0)).ok(),
Some(r#""-262144-01-01T00:00:00""#.into())
);
assert_eq!(
to_string(&NaiveDate::MAX.and_hms_nano(23, 59, 59, 1_999_999_999)).ok(),
Some(r#""+262143-12-31T23:59:60.999999999""#.into())
);
}
#[cfg(all(test, any(feature = "rustc-serialize", feature = "serde")))]
fn test_decodable_json<F, E>(from_str: F)
where
F: Fn(&str) -> Result<NaiveDateTime, E>,
E: ::std::fmt::Debug,
{
assert_eq!(
from_str(r#""2016-07-08T09:10:48.090""#).ok(),
Some(NaiveDate::from_ymd(2016, 7, 8).and_hms_milli(9, 10, 48, 90))
);
assert_eq!(
from_str(r#""2016-7-8T9:10:48.09""#).ok(),
Some(NaiveDate::from_ymd(2016, 7, 8).and_hms_milli(9, 10, 48, 90))
);
assert_eq!(
from_str(r#""2014-07-24T12:34:06""#).ok(),
Some(NaiveDate::from_ymd(2014, 7, 24).and_hms(12, 34, 6))
);
assert_eq!(
from_str(r#""0000-01-01T00:00:60""#).ok(),
Some(NaiveDate::from_ymd(0, 1, 1).and_hms_milli(0, 0, 59, 1_000))
);
assert_eq!(
from_str(r#""0-1-1T0:0:60""#).ok(),
Some(NaiveDate::from_ymd(0, 1, 1).and_hms_milli(0, 0, 59, 1_000))
);
assert_eq!(
from_str(r#""-0001-12-31T23:59:59.000000007""#).ok(),
Some(NaiveDate::from_ymd(-1, 12, 31).and_hms_nano(23, 59, 59, 7))
);
assert_eq!(from_str(r#""-262144-01-01T00:00:00""#).ok(), Some(NaiveDate::MIN.and_hms(0, 0, 0)));
assert_eq!(
from_str(r#""+262143-12-31T23:59:60.999999999""#).ok(),
Some(NaiveDate::MAX.and_hms_nano(23, 59, 59, 1_999_999_999))
);
assert_eq!(
from_str(r#""+262143-12-31T23:59:60.9999999999997""#).ok(), Some(NaiveDate::MAX.and_hms_nano(23, 59, 59, 1_999_999_999))
);
assert!(from_str(r#""""#).is_err());
assert!(from_str(r#""2016-07-08""#).is_err());
assert!(from_str(r#""09:10:48.090""#).is_err());
assert!(from_str(r#""20160708T091048.090""#).is_err());
assert!(from_str(r#""2000-00-00T00:00:00""#).is_err());
assert!(from_str(r#""2000-02-30T00:00:00""#).is_err());
assert!(from_str(r#""2001-02-29T00:00:00""#).is_err());
assert!(from_str(r#""2002-02-28T24:00:00""#).is_err());
assert!(from_str(r#""2002-02-28T23:60:00""#).is_err());
assert!(from_str(r#""2002-02-28T23:59:61""#).is_err());
assert!(from_str(r#""2016-07-08T09:10:48,090""#).is_err());
assert!(from_str(r#""2016-07-08 09:10:48.090""#).is_err());
assert!(from_str(r#""2016-007-08T09:10:48.090""#).is_err());
assert!(from_str(r#""yyyy-mm-ddThh:mm:ss.fffffffff""#).is_err());
assert!(from_str(r#"20160708000000"#).is_err());
assert!(from_str(r#"{}"#).is_err());
assert!(from_str(r#"{"date":{"ymdf":20},"time":{"secs":0,"frac":0}}"#).is_err());
assert!(from_str(r#"null"#).is_err());
}
#[cfg(all(test, feature = "rustc-serialize"))]
fn test_decodable_json_timestamp<F, E>(from_str: F)
where
F: Fn(&str) -> Result<rustc_serialize::TsSeconds, E>,
E: ::std::fmt::Debug,
{
assert_eq!(
*from_str("0").unwrap(),
NaiveDate::from_ymd(1970, 1, 1).and_hms(0, 0, 0),
"should parse integers as timestamps"
);
assert_eq!(
*from_str("-1").unwrap(),
NaiveDate::from_ymd(1969, 12, 31).and_hms(23, 59, 59),
"should parse integers as timestamps"
);
}