Skip to content

Commit

Permalink
Fix DateTime.days_since_unix_epoch
Browse files Browse the repository at this point in the history
The implementation of this method is based on the days_from_civil()
function from http://howardhinnant.github.io/date_algorithms.html. Our
implementation incorrectly used the >= operator where it should've used
the > operator, resulting in this method returning the wrong results for
certain dates.

Changelog: fixed
  • Loading branch information
yorickpeterse committed Feb 2, 2024
1 parent 8b7f0d2 commit c278334
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion std/src/std/time.inko
Expand Up @@ -376,7 +376,7 @@ class pub DateTime {
let month = @month
let era = if year >= 0 { year } else { year - 399 } / 400
let yoe = year - (era * 400)
let doy = (((153 * if month >= 2 { month - 3 } else { month + 9 }) + 2) / 5)
let doy = (((153 * if month > 2 { month - 3 } else { month + 9 }) + 2) / 5)
+ @day - 1
let doe = (yoe * 365) + (yoe / 4) - (yoe / 100) + doy

Expand Down
18 changes: 18 additions & 0 deletions std/test/std/test_time.inko
Expand Up @@ -4,6 +4,19 @@ import std.process.(sleep)
import std.test.Tests
import std.time.(DateTime, Duration, Instant)

fn ymd(year: Int, month: Int, day: Int) -> DateTime {
DateTime {
@year = year,
@month = month,
@day = day,
@hour = 12,
@minute = 0,
@second = 0,
@sub_second = 0.0,
@utc_offset = 0,
}
}

fn pub tests(t: mut Tests) {
t.test('Duration.from_secs') fn (t) {
t.equal(Duration.from_secs(1.2).to_secs, 1.2)
Expand Down Expand Up @@ -186,10 +199,12 @@ fn pub tests(t: mut Tests) {
let t1 = DateTime.from_timestamp(time: 1661538868, utc_offset: 7200)
let t2 = DateTime.from_timestamp(time: 0, utc_offset: 0)
let t3 = DateTime.from_timestamp(time: -3600, utc_offset: 0)
let t4 = ymd(2024, 2, 3)

t.equal(t1.days_since_unix_epoch, 19_230)
t.equal(t2.days_since_unix_epoch, 0)
t.equal(t3.days_since_unix_epoch, -1)
t.equal(t4.days_since_unix_epoch, 19_756)
}

t.test('DateTime.leap_year?') fn (t) {
Expand Down Expand Up @@ -232,10 +247,12 @@ fn pub tests(t: mut Tests) {
let t1 = DateTime.from_timestamp(time: 1661538868, utc_offset: 7200)
let t2 = DateTime.from_timestamp(time: 0, utc_offset: 0)
let t3 = DateTime.from_timestamp(time: -3600, utc_offset: 0)
let t4 = ymd(2024, 2, 3)

t.equal(t1.to_int, 1661538868)
t.equal(t2.to_int, 0)
t.equal(t3.to_int, -3600)
t.equal(t4.to_int, 1706961600)
}

t.test('DateTime.to_float') fn (t) {
Expand Down Expand Up @@ -269,6 +286,7 @@ fn pub tests(t: mut Tests) {
t.equal(t1.cmp(t2), Ordering.Greater)
t.equal(t2.cmp(t1), Ordering.Less)
t.equal(t1.cmp(t1), Ordering.Equal)
t.equal(ymd(2024, 2, 3).cmp(ymd(2023, 12, 14)), Ordering.Greater)
}

t.test('DateTime.==') fn (t) {
Expand Down

0 comments on commit c278334

Please sign in to comment.