Skip to content

Commit

Permalink
remove _opt suffix from TimeZone::timestamp_micros and use
Browse files Browse the repository at this point in the history
NaiveDateTime::from_timestamp_micros instead of implementing the same
logic again.
  • Loading branch information
emikitas committed Sep 13, 2023
1 parent afd8e30 commit d9b3468
Showing 1 changed file with 10 additions and 17 deletions.
27 changes: 10 additions & 17 deletions src/offset/mod.rs
Expand Up @@ -438,15 +438,13 @@ pub trait TimeZone: Sized + Clone {
/// ```
/// use chrono::{Utc, TimeZone};
///
/// assert_eq!(Utc.timestamp_micros_opt(1431648000000).unwrap().timestamp(), 1431648);
/// assert_eq!(Utc.timestamp_micros(1431648000000).unwrap().timestamp(), 1431648);
/// ```
fn timestamp_micros_opt(&self, micros: i64) -> LocalResult<DateTime<Self>> {
let (mut secs, mut micros) = (micros / 1_000_000, micros % 1_000_000);
if micros < 0 {
secs -= 1;
micros += 1_000_000;
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
}
self.timestamp_opt(secs, (micros * 1000) as u32)
}

/// Parses a string with the specified format string and returns a
Expand Down Expand Up @@ -577,20 +575,15 @@ mod tests {

#[test]
fn test_negative_micros() {
let dt = Utc.timestamp_micros_opt(-1_000_000).unwrap();
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_opt(-999_999).unwrap();
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_opt(-1).unwrap();
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_opt(-60_000_000).unwrap();
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_opt(-3_600_000_000).unwrap();
let dt = Utc.timestamp_micros(-3_600_000_000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:00:00 UTC");
}

#[test]
fn test_micros_example() {
assert_eq!(Utc.timestamp_micros_opt(1431648000000).unwrap().timestamp(), 1431648);
}
}

0 comments on commit d9b3468

Please sign in to comment.