Skip to content

Commit

Permalink
lib: Fix timeformat.parseShortDate()
Browse files Browse the repository at this point in the history
Do the "strip off time and set to midnight" step already for the
reference Date input of parse(). Substracting it afterwards previously
caused the returned date to be off by one day for time zones East of
UTC.

Test with:

    for TZ in America/New_York UTC Europe/Berlin; do pytest -k timeformat || break; done
  • Loading branch information
martinpitt committed Jun 25, 2024
1 parent 9ee4bd7 commit 00533a4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
17 changes: 10 additions & 7 deletions pkg/base1/test-timeformat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,21 +124,24 @@ QUnit.test("firstDayOfWeek", assert => {
assert.equal(timeformat.firstDayOfWeek(), 1);
});

// FIXME: This test is currently time zone dependent; parseShortDate() always
// interprets its argument as midnight UTC instead of local time; so it's even
// off by a day for any TZ east of UTC.
QUnit.skip("parsing", assert => {
QUnit.test("parsing", assert => {
cockpit.language = "en";
const en = timeformat.parseShortDate("1/20/2024");
assert.equal(en.toISOString(), "2024-01-20T00:00:00.000Z");
assert.equal(en.getDate(), 20);
assert.equal(en.getMonth(), 0); // yes, starting from 0
assert.equal(en.getFullYear(), "2024");

cockpit.language = "en_GB";
const engb = timeformat.parseShortDate("20/01/2024");
assert.equal(engb.toISOString(), "2024-01-20T00:00:00.000Z");
assert.equal(engb.getDate(), 20);
assert.equal(engb.getMonth(), 0); // yes, starting from 0
assert.equal(engb.getFullYear(), "2024");

cockpit.language = "de";
const de = timeformat.parseShortDate("20.01.2024");
assert.equal(de.toISOString(), "2024-01-20T00:00:00.000Z");
assert.equal(de.getDate(), 20);
assert.equal(de.getMonth(), 0); // yes, starting from 0
assert.equal(de.getFullYear(), "2024");
});

QUnit.start();
10 changes: 4 additions & 6 deletions pkg/lib/timeformat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,10 @@ export const distanceToNow = (t: Time, addSuffix?: boolean): string => formatDis

// Parse a string localized date like 30.06.21 to a Date Object
export function parseShortDate(dateStr: string): Date {
const parsed = parse(dateStr, dateShortFormat(), new Date());

// Strip time which may cause bugs in calendar
const time = parsed.getTime();
const timePortion = time % (3600 * 1000 * 24);
return new Date(time - timePortion);
// strip off time (i.e. set to midnight), to avoid confusing calendar widgets
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
return parse(dateStr, dateShortFormat(), today);
}

/***
Expand Down

0 comments on commit 00533a4

Please sign in to comment.