Add tests for negative timestamps / DateTime before Unix Epoch

This commit is contained in:
Nathan Fisher 2024-02-09 00:03:24 -05:00
parent b3ea308997
commit e2910695d2

View File

@ -74,7 +74,7 @@ impl DateTime {
let mut month = Some(Month::December);
while month.is_some() {
let m = month.unwrap();
if seconds < -m.seconds(year) {
if -seconds < m.seconds(year) {
break;
}
seconds += m.seconds(year);
@ -87,16 +87,17 @@ impl DateTime {
day -= 1;
}
let mut hour: i8 = 23;
while hour >= 0 && seconds < -SECONDS_PER_HOUR {
while hour > 0 && seconds < -SECONDS_PER_HOUR {
seconds += SECONDS_PER_HOUR;
hour -= 1;
}
let hour = hour.try_into().unwrap();
let mut minute: i8 = 60;
while minute >= 0 && seconds < -60 {
while minute > 0 && seconds < -60 {
seconds += 60;
minute -= 1;
}
minute -= 1;
let minute = minute.try_into().unwrap();
let second: u8 = (seconds + 60).try_into().unwrap();
Self {
@ -150,8 +151,9 @@ impl DateTime {
pub fn weekday(&self) -> Weekday {
let ts = self.timestamp_naive();
let days = ts / SECONDS_PER_DAY;
let rem = days % 7;
let mut days = ts / SECONDS_PER_DAY;
if ts < 0 { days -= 1 }
let rem = days.rem_euclid(7);
rem.try_into().unwrap()
}
@ -230,6 +232,28 @@ mod tests {
},
};
assert_eq!(dt.weekday(), Weekday::Saturday);
dt = DateTime {
year: Year::new(1965),
month: Month::February,
day: 9,
hour: 4,
minute: 4,
second: 37,
zone: TimeZone::Utc,
};
assert_eq!(dt.weekday(), Weekday::Tuesday);
dt.day -= 1;
assert_eq!(dt.weekday(), Weekday::Monday);
dt.day -= 1;
assert_eq!(dt.weekday(), Weekday::Sunday);
dt.day -= 1;
assert_eq!(dt.weekday(), Weekday::Saturday);
dt.day -= 1;
assert_eq!(dt.weekday(), Weekday::Friday);
dt.day -= 1;
assert_eq!(dt.weekday(), Weekday::Thursday);
dt.day -= 1;
assert_eq!(dt.weekday(), Weekday::Wednesday);
}
#[test]
@ -271,6 +295,22 @@ mod tests {
assert_eq!(dt, DateTime::from_timestamp(ts));
}
#[test]
fn ts_negative() {
let ts: i64 = -154382123;
let dt = DateTime {
year: Year::new(1965),
month: Month::February,
day: 9,
hour: 4,
minute: 4,
second: 37,
zone: TimeZone::Utc,
};
assert_eq!(dt.timestamp(), ts);
assert_eq!(dt, DateTime::from_timestamp(ts));
}
#[test]
fn fmt() {
let mut dt = DateTime::from_timestamp(1706571482);