Skip to content

Commit

Permalink
Merge pull request #50 from moia-oss/hack/fix-time-now
Browse files Browse the repository at this point in the history
remove `chrono` dependency from `Time::now()`
  • Loading branch information
jankeu authored Dec 13, 2023
2 parents 837747f + 45634dd commit e64e73e
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ use std::ops::MulAssign;
use std::ops::Sub;
use std::ops::SubAssign;
use std::str::FromStr;
use std::time::SystemTime;

use chrono::format::DelayedFormat;
use chrono::format::StrftimeItems;
Expand Down Expand Up @@ -167,12 +168,12 @@ impl Time {
.map(|chrono_datetime| Time::millis(chrono_datetime.timestamp_millis()))
}

/// Returns the current time instance.
/// Returns the current time instance based on `SystemTime`
///
/// Don't use this method to compare if the current time has passed a
/// certain deadline.
pub fn now() -> Time {
Time::millis(chrono::Local::now().timestamp_millis())
Time::from(SystemTime::now())
}

pub fn as_millis(&self) -> i64 {
Expand Down Expand Up @@ -332,6 +333,18 @@ impl From<Time> for std::time::SystemTime {
}
}

impl From<std::time::SystemTime> for Time {
fn from(input: std::time::SystemTime) -> Self {
if input > SystemTime::UNIX_EPOCH {
let std_dur = input.duration_since(SystemTime::UNIX_EPOCH).unwrap();
Self::millis(Duration::from(std_dur).as_millis())
} else {
let std_dur = SystemTime::UNIX_EPOCH.duration_since(input).unwrap();
Self::millis(-Duration::from(std_dur).as_millis())
}
}
}

impl Debug for Time {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
// This implementation is tailor-made, because NaiveDateTime does not support
Expand Down

0 comments on commit e64e73e

Please sign in to comment.