Skip to content

Commit

Permalink
fix(common): The date pipe should return ISO format for week and week…
Browse files Browse the repository at this point in the history
…-year as intended in the unit test. (#53879)

ISO 8601 defines
* Monday as the first day of the week.
* week 01 is the week with the first Thursday

Therefore:
Sunday Dec 31st 2023 is the last day of the last week of the year : W52 2023.

PR Close #53879
  • Loading branch information
JeanMeche authored and thePunderWoman committed Jan 31, 2024
1 parent ed8e7c7 commit cdc5e39
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 72 deletions.
17 changes: 13 additions & 4 deletions packages/common/src/i18n/format_date.ts
Expand Up @@ -462,11 +462,20 @@ function getFirstThursdayOfYear(year: number) {
);
}

function getThursdayThisWeek(datetime: Date) {
/**
* ISO Week starts on day 1 (Monday) and ends with day 0 (Sunday)
*/
export function getThursdayThisIsoWeek(datetime: Date) {
// getDay returns 0-6 range with sunday as 0.
const currentDay = datetime.getDay();

// On a Sunday, read the previous Thursday since ISO weeks start on Monday.
const deltaToThursday = currentDay === 0 ? -3 : THURSDAY - currentDay;

return createDate(
datetime.getFullYear(),
datetime.getMonth(),
datetime.getDate() + (THURSDAY - datetime.getDay()),
datetime.getDate() + deltaToThursday,
);
}

Expand All @@ -479,7 +488,7 @@ function weekGetter(size: number, monthBased = false): DateFormatter {
const today = date.getDate();
result = 1 + Math.floor((today + nbDaysBefore1stDayOfMonth) / 7);
} else {
const thisThurs = getThursdayThisWeek(date);
const thisThurs = getThursdayThisIsoWeek(date);
// Some days of a year are part of next year according to ISO 8601.
// Compute the firstThurs from the year of this week's Thursday
const firstThurs = getFirstThursdayOfYear(thisThurs.getFullYear());
Expand All @@ -496,7 +505,7 @@ function weekGetter(size: number, monthBased = false): DateFormatter {
*/
function weekNumberingYearGetter(size: number, trim = false): DateFormatter {
return function (date: Date, locale: string) {
const thisThurs = getThursdayThisWeek(date);
const thisThurs = getThursdayThisIsoWeek(date);
const weekNumberingYear = thisThurs.getFullYear();
return padNumber(
weekNumberingYear,
Expand Down

0 comments on commit cdc5e39

Please sign in to comment.