Skip to content

Commit

Permalink
Correct Unix timestamp implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
otake84 authored Jan 9, 2021
1 parent f153a1c commit 896c373
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/offset_date_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,13 @@ impl OffsetDateTime {
/// );
/// ```
pub fn unix_timestamp(self) -> i64 {
(self - Self::unix_epoch()).whole_seconds()
let days = (self.utc_datetime.date.julian_day()
- internals::Date::from_yo_unchecked(1970, 1).julian_day())
* 86_400;
let hours = self.utc_datetime.hour() as i64 * 3_600;
let minutes = self.utc_datetime.minute() as i64 * 60;
let seconds = self.utc_datetime.second() as i64;
days + hours + minutes + seconds
}

/// Get the [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time).
Expand Down
8 changes: 7 additions & 1 deletion src/primitive_date_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,13 @@ impl PrimitiveDateTime {
#[allow(deprecated)]
#[deprecated(since = "0.2.7", note = "This method assumes an offset of UTC.")]
pub fn timestamp(self) -> i64 {
(self - Self::unix_epoch()).whole_seconds()
let days = (self.date.julian_day()
- internals::Date::from_yo_unchecked(1970, 1).julian_day())
* 86_400;
let hours = self.hour() as i64 * 3_600;
let minutes = self.minute() as i64 * 60;
let seconds = self.second() as i64;
days + hours + minutes + seconds
}

/// Get the `Date` component of the `PrimitiveDateTime`.
Expand Down
4 changes: 4 additions & 0 deletions tests/offset_date_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ fn timestamp() {
.timestamp(),
3_600,
);
assert_eq!(
(OffsetDateTime::unix_epoch() - 1.nanoseconds()).timestamp(),
-1
);
}

#[test]
Expand Down
4 changes: 4 additions & 0 deletions tests/primitive_date_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ fn from_unix_timestamp() {
fn timestamp() {
assert_eq!(PrimitiveDateTime::unix_epoch().timestamp(), 0);
assert_eq!(date!(2019 - 01 - 01).midnight().timestamp(), 1_546_300_800);
assert_eq!(
(PrimitiveDateTime::unix_epoch() - 1.nanoseconds()).timestamp(),
-1
);
}

#[test]
Expand Down

0 comments on commit 896c373

Please sign in to comment.