Skip to content

Commit 896c373

Browse files
authored
Correct Unix timestamp implementation
1 parent f153a1c commit 896c373

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

src/offset_date_time.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,13 @@ impl OffsetDateTime {
298298
/// );
299299
/// ```
300300
pub fn unix_timestamp(self) -> i64 {
301-
(self - Self::unix_epoch()).whole_seconds()
301+
let days = (self.utc_datetime.date.julian_day()
302+
- internals::Date::from_yo_unchecked(1970, 1).julian_day())
303+
* 86_400;
304+
let hours = self.utc_datetime.hour() as i64 * 3_600;
305+
let minutes = self.utc_datetime.minute() as i64 * 60;
306+
let seconds = self.utc_datetime.second() as i64;
307+
days + hours + minutes + seconds
302308
}
303309

304310
/// Get the [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time).

src/primitive_date_time.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,13 @@ impl PrimitiveDateTime {
132132
#[allow(deprecated)]
133133
#[deprecated(since = "0.2.7", note = "This method assumes an offset of UTC.")]
134134
pub fn timestamp(self) -> i64 {
135-
(self - Self::unix_epoch()).whole_seconds()
135+
let days = (self.date.julian_day()
136+
- internals::Date::from_yo_unchecked(1970, 1).julian_day())
137+
* 86_400;
138+
let hours = self.hour() as i64 * 3_600;
139+
let minutes = self.minute() as i64 * 60;
140+
let seconds = self.second() as i64;
141+
days + hours + minutes + seconds
136142
}
137143

138144
/// Get the `Date` component of the `PrimitiveDateTime`.

tests/offset_date_time.rs

+4
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,10 @@ fn timestamp() {
123123
.timestamp(),
124124
3_600,
125125
);
126+
assert_eq!(
127+
(OffsetDateTime::unix_epoch() - 1.nanoseconds()).timestamp(),
128+
-1
129+
);
126130
}
127131

128132
#[test]

tests/primitive_date_time.rs

+4
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ fn from_unix_timestamp() {
4545
fn timestamp() {
4646
assert_eq!(PrimitiveDateTime::unix_epoch().timestamp(), 0);
4747
assert_eq!(date!(2019 - 01 - 01).midnight().timestamp(), 1_546_300_800);
48+
assert_eq!(
49+
(PrimitiveDateTime::unix_epoch() - 1.nanoseconds()).timestamp(),
50+
-1
51+
);
4852
}
4953

5054
#[test]

0 commit comments

Comments
 (0)