Skip to content

Commit

Permalink
impl
Browse files Browse the repository at this point in the history
  • Loading branch information
zhuxiujia committed Jul 19, 2022
1 parent b55ff61 commit ff012bf
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 6 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
49 changes: 45 additions & 4 deletions src/datetime.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<Duration> for DateTime{
type Output = DateTime;

fn add(self, rhs: Duration) -> Self::Output {
self.add(rhs)
}
}

impl Sub<Duration> for DateTime{
type Output = DateTime;

fn sub(self, rhs: Duration) -> Self::Output {
self.sub(rhs)
}
}


Expand Down Expand Up @@ -155,10 +181,16 @@ impl From<DateTime> 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)
}
}
}

Expand Down Expand Up @@ -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]
Expand All @@ -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);
}
}

0 comments on commit ff012bf

Please sign in to comment.