Skip to content

Commit

Permalink
Polyfill: 0-based month in ISODateToEpochDays
Browse files Browse the repository at this point in the history
While investigating #2985 I noticed that ISODateToEpochDays was defined
differently between the spec text and the reference code. Use 0-based
months as in the spec text, to avoid confusion when comparing the two.

Also I noticed that it can now be implemented more efficiently with
GetUTCEpochMilliseconds.
  • Loading branch information
ptomato authored and Ms2ger committed Oct 3, 2024
1 parent deff8b1 commit 981ab0f
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions polyfill/lib/ecmascript.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2858,8 +2858,8 @@ export function UnbalanceDateDurationRelative(dateDuration, plainRelativeTo) {
// balance years, months, and weeks down to days
const isoDate = TemporalObjectToISODateRecord(plainRelativeTo);
const later = CalendarDateAdd(GetSlot(plainRelativeTo, CALENDAR), isoDate, yearsMonthsWeeksDuration, 'constrain');
const epochDaysEarlier = ISODateToEpochDays(isoDate.year, isoDate.month, isoDate.day);
const epochDaysLater = ISODateToEpochDays(later.year, later.month, later.day);
const epochDaysEarlier = ISODateToEpochDays(isoDate.year, isoDate.month - 1, isoDate.day);
const epochDaysLater = ISODateToEpochDays(later.year, later.month - 1, later.day);
const yearsMonthsWeeksInDays = epochDaysLater - epochDaysEarlier;
return dateDuration.days + yearsMonthsWeeksInDays;
}
Expand Down Expand Up @@ -3142,10 +3142,9 @@ function CombineDateAndNormalizedTimeDuration(dateDuration, norm) {
return { date: dateDuration, norm };
}

// Caution: month is 0-based
function ISODateToEpochDays(y, m, d) {
// This is inefficient, but we use GetUTCEpochNanoseconds to avoid duplicating
// the workarounds for legacy Date. (see that function for explanation)
return GetUTCEpochNanoseconds(y, m, d, 0, 0, 0, 0, 0, 0).divide(DAY_NANOS).toJSNumber();
return GetUTCEpochMilliseconds(y, m + 1, d, 0, 0, 0, 0) / DAY_MS;
}

export function DifferenceISODate(y1, m1, d1, y2, m2, d2, largestUnit = 'days') {
Expand Down Expand Up @@ -3185,7 +3184,8 @@ export function DifferenceISODate(y1, m1, d1, y2, m2, d2, largestUnit = 'days')
const constrained = ConstrainISODate(intermediate.year, intermediate.month, d1);

let weeks = 0;
let days = ISODateToEpochDays(y2, m2, d2) - ISODateToEpochDays(constrained.year, constrained.month, constrained.day);
let days =
ISODateToEpochDays(y2, m2 - 1, d2) - ISODateToEpochDays(constrained.year, constrained.month - 1, constrained.day);

if (largestUnit === 'week') {
weeks = MathTrunc(days / 7);
Expand Down

0 comments on commit 981ab0f

Please sign in to comment.