Skip to content

Commit

Permalink
Add TimeZone::timestamp_micros
Browse files Browse the repository at this point in the history
  • Loading branch information
Eden Mikitas authored and Eden Mikitas committed Sep 12, 2023
1 parent 03fb98c commit afd8e30
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/offset/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,24 @@ 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_opt(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;
}
self.timestamp_opt(secs, (micros * 1000) as u32)
}

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

#[test]
fn test_negative_micros() {
let dt = Utc.timestamp_micros_opt(-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();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59.000001 UTC");
let dt = Utc.timestamp_micros_opt(-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();
assert_eq!(dt.to_string(), "1969-12-31 23:59:00 UTC");
let dt = Utc.timestamp_micros_opt(-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 afd8e30

Please sign in to comment.