use std::{str, fmt, hash};
use std::ops::{Add, Sub, AddAssign, SubAssign};
use num_traits::ToPrimitive;
use oldtime::Duration as OldDuration;
use {Weekday, Timelike, Datelike};
use div::div_mod_floor;
use naive::{NaiveTime, NaiveDate, IsoWeek};
use format::{Item, Numeric, Pad, Fixed};
use format::{parse, Parsed, ParseError, ParseResult, DelayedFormat, StrftimeItems};
const MAX_SECS_BITS: usize = 44;
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
pub struct NaiveDateTime {
date: NaiveDate,
time: NaiveTime,
}
impl NaiveDateTime {
#[inline]
pub fn new(date: NaiveDate, time: NaiveTime) -> NaiveDateTime {
NaiveDateTime { date: date, time: 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: date, time: time }),
(_, _) => None,
}
}
pub fn parse_from_str(s: &str, fmt: &str) -> ParseResult<NaiveDateTime> {
let mut parsed = Parsed::new();
try!(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 {
let ndays = i64::from(self.date.num_days_from_ce());
let nseconds = i64::from(self.time.num_seconds_from_midnight());
(ndays - 719_163) * 86_400 + nseconds
}
#[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_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 = try_opt!(self.date.checked_add_signed(OldDuration::seconds(rhs)));
Some(NaiveDateTime { date: date, time: 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 = try_opt!(self.date.checked_sub_signed(OldDuration::seconds(rhs)));
Some(NaiveDateTime { date: date, time: time })
}
pub fn signed_duration_since(self, rhs: NaiveDateTime) -> OldDuration {
self.date.signed_duration_since(rhs.date) + self.time.signed_duration_since(rhs.time)
}
#[inline]
pub fn format_with_items<'a, I>(&self, items: I) -> DelayedFormat<I>
where I: Iterator<Item=Item<'a>> + Clone {
DelayedFormat::new(Some(self.date), Some(self.time), items)
}
#[inline]
pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
self.format_with_items(StrftimeItems::new(fmt))
}
}
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 })
}
}
#[cfg_attr(feature = "cargo-clippy", allow(derive_hash_xor_eq))]
impl hash::Hash for NaiveDateTime {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.date.hash(state);
self.time.hash(state);
}
}
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: &'static [Item<'static>] = &[
Item::Space(""), Item::Numeric(Numeric::Year, Pad::Zero),
Item::Space(""), Item::Literal("-"),
Item::Space(""), Item::Numeric(Numeric::Month, Pad::Zero),
Item::Space(""), Item::Literal("-"),
Item::Space(""), Item::Numeric(Numeric::Day, Pad::Zero),
Item::Space(""), Item::Literal("T"), Item::Space(""), Item::Numeric(Numeric::Hour, Pad::Zero),
Item::Space(""), Item::Literal(":"),
Item::Space(""), Item::Numeric(Numeric::Minute, Pad::Zero),
Item::Space(""), Item::Literal(":"),
Item::Space(""), Item::Numeric(Numeric::Second, Pad::Zero),
Item::Fixed(Fixed::Nanosecond), Item::Space(""),
];
let mut parsed = Parsed::new();
try!(parse(&mut parsed, s, ITEMS.iter().cloned()));
parsed.to_naive_datetime_with_offset(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
{
use naive::{MIN_DATE, MAX_DATE};
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(&MIN_DATE.and_hms(0, 0, 0)).ok(),
Some(r#""-262144-01-01T00:00:00""#.into()));
assert_eq!(
to_string(&MAX_DATE.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
{
use naive::{MIN_DATE, MAX_DATE};
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(MIN_DATE.and_hms(0, 0, 0)));
assert_eq!(
from_str(r#""+262143-12-31T23:59:60.999999999""#).ok(),
Some(MAX_DATE.and_hms_nano(23, 59, 59, 1_999_999_999)));
assert_eq!(
from_str(r#""+262143-12-31T23:59:60.9999999999997""#).ok(), Some(MAX_DATE.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"
);
}
#[cfg(feature = "rustc-serialize")]
pub mod rustc_serialize {
use std::ops::Deref;
use super::NaiveDateTime;
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
impl Encodable for NaiveDateTime {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
format!("{:?}", self).encode(s)
}
}
impl Decodable for NaiveDateTime {
fn decode<D: Decoder>(d: &mut D) -> Result<NaiveDateTime, D::Error> {
d.read_str()?.parse().map_err(|_| d.error("invalid date time string"))
}
}
#[derive(Debug)]
#[deprecated(since = "1.4.2",
note = "RustcSerialize will be removed before chrono 1.0, use Serde instead")]
pub struct TsSeconds(NaiveDateTime);
#[allow(deprecated)]
impl From<TsSeconds> for NaiveDateTime {
#[allow(deprecated)]
fn from(obj: TsSeconds) -> NaiveDateTime {
obj.0
}
}
#[allow(deprecated)]
impl Deref for TsSeconds {
type Target = NaiveDateTime;
#[allow(deprecated)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[allow(deprecated)]
impl Decodable for TsSeconds {
#[allow(deprecated)]
fn decode<D: Decoder>(d: &mut D) -> Result<TsSeconds, D::Error> {
Ok(TsSeconds(
NaiveDateTime::from_timestamp_opt(d.read_i64()?, 0)
.ok_or_else(|| d.error("invalid timestamp"))?))
}
}
#[cfg(test)] use rustc_serialize::json;
#[test]
fn test_encodable() {
super::test_encodable_json(json::encode);
}
#[test]
fn test_decodable() {
super::test_decodable_json(json::decode);
}
#[test]
fn test_decodable_timestamps() {
super::test_decodable_json_timestamp(json::decode);
}
}
#[cfg(feature = "serde")]
pub mod serde {
use std::fmt;
use super::{NaiveDateTime};
use serdelib::{ser, de};
impl ser::Serialize for NaiveDateTime {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer
{
struct FormatWrapped<'a, D: 'a> {
inner: &'a D
}
impl<'a, D: fmt::Debug> fmt::Display for FormatWrapped<'a, D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}
serializer.collect_str(&FormatWrapped { inner: &self })
}
}
struct NaiveDateTimeVisitor;
impl<'de> de::Visitor<'de> for NaiveDateTimeVisitor {
type Value = NaiveDateTime;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result
{
write!(formatter, "a formatted date and time string")
}
fn visit_str<E>(self, value: &str) -> Result<NaiveDateTime, E>
where E: de::Error
{
value.parse().map_err(|err| E::custom(format!("{}", err)))
}
}
impl<'de> de::Deserialize<'de> for NaiveDateTime {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: de::Deserializer<'de>
{
deserializer.deserialize_str(NaiveDateTimeVisitor)
}
}
pub mod ts_seconds {
use std::fmt;
use serdelib::{ser, de};
use NaiveDateTime;
pub fn deserialize<'de, D>(d: D) -> Result<NaiveDateTime, D::Error>
where D: de::Deserializer<'de>
{
Ok(try!(d.deserialize_i64(NaiveDateTimeFromSecondsVisitor)))
}
pub fn serialize<S>(dt: &NaiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer
{
serializer.serialize_i64(dt.timestamp())
}
struct NaiveDateTimeFromSecondsVisitor;
impl<'de> de::Visitor<'de> for NaiveDateTimeFromSecondsVisitor {
type Value = NaiveDateTime;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result
{
write!(formatter, "a unix timestamp")
}
fn visit_i64<E>(self, value: i64) -> Result<NaiveDateTime, E>
where E: de::Error
{
NaiveDateTime::from_timestamp_opt(value, 0)
.ok_or_else(|| E::custom(format!("value is not a legal timestamp: {}", value)))
}
fn visit_u64<E>(self, value: u64) -> Result<NaiveDateTime, E>
where E: de::Error
{
NaiveDateTime::from_timestamp_opt(value as i64, 0)
.ok_or_else(|| E::custom(format!("value is not a legal timestamp: {}", value)))
}
}
}
#[cfg(test)] extern crate serde_json;
#[cfg(test)] extern crate bincode;
#[test]
fn test_serde_serialize() {
super::test_encodable_json(self::serde_json::to_string);
}
#[test]
fn test_serde_deserialize() {
super::test_decodable_json(|input| self::serde_json::from_str(&input));
}
#[test]
fn test_serde_bincode() {
use naive::NaiveDate;
use self::bincode::{Infinite, serialize, deserialize};
let dt = NaiveDate::from_ymd(2016, 7, 8).and_hms_milli(9, 10, 48, 90);
let encoded = serialize(&dt, Infinite).unwrap();
let decoded: NaiveDateTime = deserialize(&encoded).unwrap();
assert_eq!(dt, decoded);
}
}
#[cfg(test)]
mod tests {
use super::NaiveDateTime;
use Datelike;
use naive::{NaiveDate, MIN_DATE, MAX_DATE};
use std::i64;
use oldtime::Duration;
#[test]
fn test_datetime_from_timestamp() {
let from_timestamp = |secs| NaiveDateTime::from_timestamp_opt(secs, 0);
let ymdhms = |y,m,d,h,n,s| NaiveDate::from_ymd(y,m,d).and_hms(h,n,s);
assert_eq!(from_timestamp(-1), Some(ymdhms(1969, 12, 31, 23, 59, 59)));
assert_eq!(from_timestamp(0), Some(ymdhms(1970, 1, 1, 0, 0, 0)));
assert_eq!(from_timestamp(1), Some(ymdhms(1970, 1, 1, 0, 0, 1)));
assert_eq!(from_timestamp(1_000_000_000), Some(ymdhms(2001, 9, 9, 1, 46, 40)));
assert_eq!(from_timestamp(0x7fffffff), Some(ymdhms(2038, 1, 19, 3, 14, 7)));
assert_eq!(from_timestamp(i64::MIN), None);
assert_eq!(from_timestamp(i64::MAX), None);
}
#[test]
fn test_datetime_add() {
fn check((y,m,d,h,n,s): (i32,u32,u32,u32,u32,u32), rhs: Duration,
result: Option<(i32,u32,u32,u32,u32,u32)>) {
let lhs = NaiveDate::from_ymd(y, m, d).and_hms(h, n, s);
let sum = result.map(|(y,m,d,h,n,s)| NaiveDate::from_ymd(y, m, d).and_hms(h, n, s));
assert_eq!(lhs.checked_add_signed(rhs), sum);
assert_eq!(lhs.checked_sub_signed(-rhs), sum);
};
check((2014,5,6, 7,8,9), Duration::seconds(3600 + 60 + 1), Some((2014,5,6, 8,9,10)));
check((2014,5,6, 7,8,9), Duration::seconds(-(3600 + 60 + 1)), Some((2014,5,6, 6,7,8)));
check((2014,5,6, 7,8,9), Duration::seconds(86399), Some((2014,5,7, 7,8,8)));
check((2014,5,6, 7,8,9), Duration::seconds(86_400 * 10), Some((2014,5,16, 7,8,9)));
check((2014,5,6, 7,8,9), Duration::seconds(-86_400 * 10), Some((2014,4,26, 7,8,9)));
check((2014,5,6, 7,8,9), Duration::seconds(86_400 * 10), Some((2014,5,16, 7,8,9)));
let max_days_from_year_0 = MAX_DATE.signed_duration_since(NaiveDate::from_ymd(0,1,1));
check((0,1,1, 0,0,0), max_days_from_year_0, Some((MAX_DATE.year(),12,31, 0,0,0)));
check((0,1,1, 0,0,0), max_days_from_year_0 + Duration::seconds(86399),
Some((MAX_DATE.year(),12,31, 23,59,59)));
check((0,1,1, 0,0,0), max_days_from_year_0 + Duration::seconds(86_400), None);
check((0,1,1, 0,0,0), Duration::max_value(), None);
let min_days_from_year_0 = MIN_DATE.signed_duration_since(NaiveDate::from_ymd(0,1,1));
check((0,1,1, 0,0,0), min_days_from_year_0, Some((MIN_DATE.year(),1,1, 0,0,0)));
check((0,1,1, 0,0,0), min_days_from_year_0 - Duration::seconds(1), None);
check((0,1,1, 0,0,0), Duration::min_value(), None);
}
#[test]
fn test_datetime_sub() {
let ymdhms = |y,m,d,h,n,s| NaiveDate::from_ymd(y,m,d).and_hms(h,n,s);
let since = NaiveDateTime::signed_duration_since;
assert_eq!(since(ymdhms(2014, 5, 6, 7, 8, 9), ymdhms(2014, 5, 6, 7, 8, 9)),
Duration::zero());
assert_eq!(since(ymdhms(2014, 5, 6, 7, 8, 10), ymdhms(2014, 5, 6, 7, 8, 9)),
Duration::seconds(1));
assert_eq!(since(ymdhms(2014, 5, 6, 7, 8, 9), ymdhms(2014, 5, 6, 7, 8, 10)),
Duration::seconds(-1));
assert_eq!(since(ymdhms(2014, 5, 7, 7, 8, 9), ymdhms(2014, 5, 6, 7, 8, 10)),
Duration::seconds(86399));
assert_eq!(since(ymdhms(2001, 9, 9, 1, 46, 39), ymdhms(1970, 1, 1, 0, 0, 0)),
Duration::seconds(999_999_999));
}
#[test]
fn test_datetime_addassignment() {
let ymdhms = |y,m,d,h,n,s| NaiveDate::from_ymd(y,m,d).and_hms(h,n,s);
let mut date = ymdhms(2016, 10, 1, 10, 10, 10);
date += Duration::minutes(10_000_000);
assert_eq!(date, ymdhms(2035, 10, 6, 20, 50, 10));
date += Duration::days(10);
assert_eq!(date, ymdhms(2035, 10, 16, 20, 50, 10));
}
#[test]
fn test_datetime_subassignment() {
let ymdhms = |y,m,d,h,n,s| NaiveDate::from_ymd(y,m,d).and_hms(h,n,s);
let mut date = ymdhms(2016, 10, 1, 10, 10, 10);
date -= Duration::minutes(10_000_000);
assert_eq!(date, ymdhms(1997, 9, 26, 23, 30, 10));
date -= Duration::days(10);
assert_eq!(date, ymdhms(1997, 9, 16, 23, 30, 10));
}
#[test]
fn test_datetime_timestamp() {
let to_timestamp = |y,m,d,h,n,s| NaiveDate::from_ymd(y,m,d).and_hms(h,n,s).timestamp();
assert_eq!(to_timestamp(1969, 12, 31, 23, 59, 59), -1);
assert_eq!(to_timestamp(1970, 1, 1, 0, 0, 0), 0);
assert_eq!(to_timestamp(1970, 1, 1, 0, 0, 1), 1);
assert_eq!(to_timestamp(2001, 9, 9, 1, 46, 40), 1_000_000_000);
assert_eq!(to_timestamp(2038, 1, 19, 3, 14, 7), 0x7fffffff);
}
#[test]
fn test_datetime_from_str() {
let valid = [
"2015-2-18T23:16:9.15",
"-77-02-18T23:16:09",
" +82701 - 05 - 6 T 15 : 9 : 60.898989898989 ",
];
for &s in &valid {
let d = match s.parse::<NaiveDateTime>() {
Ok(d) => d,
Err(e) => panic!("parsing `{}` has failed: {}", s, e)
};
let s_ = format!("{:?}", d);
let d_ = match s_.parse::<NaiveDateTime>() {
Ok(d) => d,
Err(e) => panic!("`{}` is parsed into `{:?}`, but reparsing that has failed: {}",
s, d, e)
};
assert!(d == d_, "`{}` is parsed into `{:?}`, but reparsed result \
`{:?}` does not match", s, d, d_);
}
assert!("".parse::<NaiveDateTime>().is_err());
assert!("x".parse::<NaiveDateTime>().is_err());
assert!("15".parse::<NaiveDateTime>().is_err());
assert!("15:8:9".parse::<NaiveDateTime>().is_err());
assert!("15-8-9".parse::<NaiveDateTime>().is_err());
assert!("2015-15-15T15:15:15".parse::<NaiveDateTime>().is_err());
assert!("2012-12-12T12:12:12x".parse::<NaiveDateTime>().is_err());
assert!("2012-123-12T12:12:12".parse::<NaiveDateTime>().is_err());
assert!("+ 82701-123-12T12:12:12".parse::<NaiveDateTime>().is_err());
assert!("+802701-123-12T12:12:12".parse::<NaiveDateTime>().is_err()); }
#[test]
fn test_datetime_parse_from_str() {
let ymdhms = |y,m,d,h,n,s| NaiveDate::from_ymd(y,m,d).and_hms(h,n,s);
let ymdhmsn =
|y,m,d,h,n,s,nano| NaiveDate::from_ymd(y, m, d).and_hms_nano(h, n, s, nano);
assert_eq!(NaiveDateTime::parse_from_str("2014-5-7T12:34:56+09:30", "%Y-%m-%dT%H:%M:%S%z"),
Ok(ymdhms(2014, 5, 7, 12, 34, 56))); assert_eq!(NaiveDateTime::parse_from_str("2015-W06-1 000000", "%G-W%V-%u%H%M%S"),
Ok(ymdhms(2015, 2, 2, 0, 0, 0)));
assert_eq!(NaiveDateTime::parse_from_str("Fri, 09 Aug 2013 23:54:35 GMT",
"%a, %d %b %Y %H:%M:%S GMT"),
Ok(ymdhms(2013, 8, 9, 23, 54, 35)));
assert!(NaiveDateTime::parse_from_str("Sat, 09 Aug 2013 23:54:35 GMT",
"%a, %d %b %Y %H:%M:%S GMT").is_err());
assert!(NaiveDateTime::parse_from_str("2014-5-7 12:3456", "%Y-%m-%d %H:%M:%S").is_err());
assert!(NaiveDateTime::parse_from_str("12:34:56", "%H:%M:%S").is_err()); assert_eq!(NaiveDateTime::parse_from_str("1441497364", "%s"),
Ok(ymdhms(2015, 9, 5, 23, 56, 4)));
assert_eq!(NaiveDateTime::parse_from_str("1283929614.1234", "%s.%f"),
Ok(ymdhmsn(2010, 9, 8, 7, 6, 54, 1234)));
assert_eq!(NaiveDateTime::parse_from_str("1441497364.649", "%s%.3f"),
Ok(ymdhmsn(2015, 9, 5, 23, 56, 4, 649000000)));
assert_eq!(NaiveDateTime::parse_from_str("1497854303.087654", "%s%.6f"),
Ok(ymdhmsn(2017, 6, 19, 6, 38, 23, 87654000)));
assert_eq!(NaiveDateTime::parse_from_str("1437742189.918273645", "%s%.9f"),
Ok(ymdhmsn(2015, 7, 24, 12, 49, 49, 918273645)));
}
#[test]
fn test_datetime_format() {
let dt = NaiveDate::from_ymd(2010, 9, 8).and_hms_milli(7, 6, 54, 321);
assert_eq!(dt.format("%c").to_string(), "Wed Sep 8 07:06:54 2010");
assert_eq!(dt.format("%s").to_string(), "1283929614");
assert_eq!(dt.format("%t%n%%%n%t").to_string(), "\t\n%\n\t");
let dt = NaiveDate::from_ymd(2012, 6, 30).and_hms_milli(23, 59, 59, 1_000);
assert_eq!(dt.format("%c").to_string(), "Sat Jun 30 23:59:60 2012");
assert_eq!(dt.format("%s").to_string(), "1341100799"); }
#[test]
fn test_datetime_add_sub_invariant() { let base = NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0);
let t = -946684799990000;
let time = base + Duration::microseconds(t);
assert_eq!(t, time.signed_duration_since(base).num_microseconds().unwrap());
}
}