Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add time zone timestamp micros #1285

Merged
merged 2 commits into from Sep 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 33 additions & 5 deletions src/offset/mod.rs
Expand Up @@ -403,12 +403,10 @@
/// };
/// ```
fn timestamp_millis_opt(&self, millis: i64) -> LocalResult<DateTime<Self>> {
let (mut secs, mut millis) = (millis / 1000, millis % 1000);
if millis < 0 {
secs -= 1;
millis += 1000;
match NaiveDateTime::from_timestamp_millis(millis) {
Some(dt) => LocalResult::Single(self.from_utc_datetime(&dt)),
None => LocalResult::None,

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

View check run for this annotation

Codecov / codecov/patch

src/offset/mod.rs#L408

Added line #L408 was not covered by tests
}
self.timestamp_opt(secs, millis as u32 * 1_000_000)
}

/// Makes a new `DateTime` from the number of non-leap nanoseconds
Expand All @@ -433,6 +431,22 @@
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 @@ -558,4 +572,18 @@
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");
}
}