Skip to content

Commit

Permalink
Add TimeZone::timestamp_micros
Browse files Browse the repository at this point in the history
Use NaiveDateTime::from_timestamp_micros instead of implementing
the same logic again.
  • Loading branch information
Eden Mikitas authored and emikitas committed Sep 13, 2023
1 parent 03fb98c commit 81708eb
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/offset/mod.rs
Expand Up @@ -431,6 +431,22 @@ pub trait TimeZone: Sized + Clone {
self.timestamp_opt(secs, nanos as u32).unwrap()
}

/// Makes a new `DateTime` from the number of non-leap microseconds
/// since January 1, 1970 0:00:00 UTC (aka "UNIX timestamp").
///
/// #Example
/// ```
/// use chrono::{Utc, TimeZone};
///
/// assert_eq!(Utc.timestamp_micros(1431648000000).unwrap().timestamp(), 1431648);
/// ```
fn timestamp_micros(&self, micros: i64) -> LocalResult<DateTime<Self>> {
match NaiveDateTime::from_timestamp_micros(micros) {
Some(dt) => LocalResult::Single(self.from_utc_datetime(&dt)),
None => LocalResult::None,

Check warning on line 446 in src/offset/mod.rs

View check run for this annotation

Codecov / codecov/patch

src/offset/mod.rs#L446

Added line #L446 was not covered by tests
}
}

/// Parses a string with the specified format string and returns a
/// `DateTime` with the current offset.
///
Expand Down Expand Up @@ -556,4 +572,18 @@ mod tests {
Utc.timestamp_nanos(i64::default());
Utc.timestamp_nanos(i64::min_value());
}

#[test]
fn test_negative_micros() {
let dt = Utc.timestamp_micros(-1_000_000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59 UTC");
let dt = Utc.timestamp_micros(-999_999).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59.000001 UTC");
let dt = Utc.timestamp_micros(-1).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59.999999 UTC");
let dt = Utc.timestamp_micros(-60_000_000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:00 UTC");
let dt = Utc.timestamp_micros(-3_600_000_000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:00:00 UTC");
}
}

0 comments on commit 81708eb

Please sign in to comment.