diff --git a/Cargo.toml b/Cargo.toml index dc45d94..ded9a3d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fastdate" -version = "0.1.1" +version = "0.1.2" edition = "2021" description = "Rust fast date carte" readme = "Readme.md" diff --git a/README.md b/README.md index 1f8f768..c69f331 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,10 @@ fn main(){ DateTime::now(); //utc time now DateTime::utc(); - + // add + DateTime::now() + Duration::from_secs(1); + // sub + DateTime::now() - Duration::from_secs(1); //from str let datetime=DateTime::from_str("1234-12-13 11:12:13.123456"); //to_string() diff --git a/src/datetime.rs b/src/datetime.rs index 5e9f281..0c0126d 100644 --- a/src/datetime.rs +++ b/src/datetime.rs @@ -1,6 +1,6 @@ use std::cmp; use std::fmt::{self, Display, Formatter, Pointer}; -use std::ops::Deref; +use std::ops::{Add, Deref, Sub}; use std::str::FromStr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use once_cell::sync::Lazy; @@ -50,6 +50,32 @@ impl DateTime { Self::from(SystemTime::now() - Duration::from_secs(offset as u64)) } } + + pub fn add(self, d: Duration) -> Self { + let systime = SystemTime::from(self) + d; + Self::from(systime) + } + + pub fn sub(self, d: Duration) -> Self { + let systime = SystemTime::from(self) - d; + Self::from(systime) + } +} + +impl Add for DateTime{ + type Output = DateTime; + + fn add(self, rhs: Duration) -> Self::Output { + self.add(rhs) + } +} + +impl Sub for DateTime{ + type Output = DateTime; + + fn sub(self, rhs: Duration) -> Self::Output { + self.sub(rhs) + } } @@ -155,10 +181,16 @@ impl From for SystemTime { ydays += 1; } let days = (v.year as u64 - 1970) * 365 + leap_years as u64 + ydays; - UNIX_EPOCH - + Duration::from_secs( + let sec = Duration::from_secs( v.sec as u64 + v.min as u64 * 60 + v.hour as u64 * 3600 + days * 86400, - ) + ); + if v.micro > 0 { + UNIX_EPOCH + + sec + Duration::from_micros(v.micro as u64) + } else { + UNIX_EPOCH + + sec - Duration::from_micros(v.micro as u64) + } } } @@ -307,6 +339,7 @@ impl<'de> Deserialize<'de> for DateTime { #[cfg(test)] mod tests { use std::str::FromStr; + use std::time::Duration; use crate::DateTime; #[test] @@ -321,4 +354,12 @@ mod tests { let d = DateTime::now(); println!("{}", d); } + + #[test] + fn test_date_utc_add() { + let d = DateTime::now(); + let added = d + Duration::from_secs(1); + println!("{},{}", d, added); + assert_eq!(d.add(Duration::from_secs(1)), added); + } }