diff --git a/src/common/time/src/date.rs b/src/common/time/src/date.rs index e9b1d76246c7..b94c483e3081 100644 --- a/src/common/time/src/date.rs +++ b/src/common/time/src/date.rs @@ -82,6 +82,10 @@ impl Date { pub fn to_chrono_date(&self) -> Option { NaiveDate::from_num_days_from_ce_opt(UNIX_EPOCH_FROM_CE + self.0) } + + pub fn to_secs(&self) -> i64 { + (self.0 as i64) * 24 * 3600 + } } #[cfg(test)] @@ -132,4 +136,14 @@ mod tests { let d: Date = 42.into(); assert_eq!(42, d.val()); } + + #[test] + fn test_to_secs() { + let d = Date::from_str("1970-01-01").unwrap(); + assert_eq!(d.to_secs(), 0); + let d = Date::from_str("1970-01-02").unwrap(); + assert_eq!(d.to_secs(), 24 * 3600); + let d = Date::from_str("1970-01-03").unwrap(); + assert_eq!(d.to_secs(), 2 * 24 * 3600); + } } diff --git a/src/common/time/src/datetime.rs b/src/common/time/src/datetime.rs index 426d3f106971..05d4884e95f5 100644 --- a/src/common/time/src/datetime.rs +++ b/src/common/time/src/datetime.rs @@ -50,6 +50,12 @@ impl From for serde_json::Value { } } +impl From for DateTime { + fn from(value: NaiveDateTime) -> Self { + DateTime::from(value.timestamp()) + } +} + impl FromStr for DateTime { type Err = Error; @@ -88,7 +94,7 @@ impl DateTime { } pub fn to_chrono_datetime(&self) -> Option { - NaiveDateTime::from_timestamp_millis(self.0) + NaiveDateTime::from_timestamp_opt(self.0, 0) } } diff --git a/src/common/time/src/time.rs b/src/common/time/src/time.rs index 7400e22c0fe5..8c3aeba8663e 100644 --- a/src/common/time/src/time.rs +++ b/src/common/time/src/time.rs @@ -77,6 +77,19 @@ impl Time { self.value } + /// Convert a time to given time unit. + /// Return `None` if conversion causes overflow. + pub fn convert_to(&self, unit: TimeUnit) -> Option