Skip to content

Commit

Permalink
#1144@trivial: Updates Date ISO week function to a more battle tested.
Browse files Browse the repository at this point in the history
  • Loading branch information
capricorn86 committed Oct 27, 2023
1 parent 49d489d commit a56ed6a
Showing 1 changed file with 6 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,19 @@ export default class HTMLInputElementDateUtility {
* @returns Iso-week string.
*/
public static dateIsoWeek(date: Date | number): string {
const parsedDate = typeof date === 'number' ? new Date(date) : date;
date = typeof date === 'number' ? new Date(date) : date;
// Copy date so don't modify original
const newDate = new Date(
Date.UTC(parsedDate.getFullYear(), parsedDate.getMonth(), parsedDate.getDate())
);
date = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
newDate.setUTCDate(newDate.getUTCDate() + 4 - (newDate.getUTCDay() || 7));
date.setUTCDate(date.getUTCDate() + 4 - (date.getUTCDay() || 7));
// Get first day of year
const yearStart = new Date(Date.UTC(newDate.getUTCFullYear(), 0, 1));
const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
// Calculate full weeks to nearest Thursday
const weekNo = Math.ceil(
((<number>(<unknown>newDate) - <number>(<unknown>yearStart)) / 86400000 + 1) / 7
((<number>(<unknown>date) - <number>(<unknown>yearStart)) / 86400000 + 1) / 7
);
return `${newDate.getUTCFullYear()}-W${weekNo < 10 ? '0' : ''}${weekNo}`;
return `${date.getUTCFullYear()}-W${weekNo < 10 ? '0' : ''}${weekNo}`;
}

/**
Expand Down

0 comments on commit a56ed6a

Please sign in to comment.