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 f26b084 commit 49d489d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,28 @@ export default class HTMLInputElementDateUtility {
/**
* Returns iso week number from given date
*
* @see https://stackoverflow.com/a/6117889
* @param date Date or number.
* @returns Iso-week string.
*/
public static dateIsoWeek(date: Date | number): string {
date = new Date(date);
const day = (date.getUTCDay() + 6) % 7;
date.setUTCDate(date.getUTCDate() - day + 3);
const firstThursday = date.getTime();
date.setUTCMonth(0, 1);
if (date.getUTCDay() !== 4) {
date.setUTCMonth(0, 1 + ((4 - date.getUTCDay() + 7) % 7));
}
return (
date.getUTCFullYear() +
'-W' +
String(1 + Math.ceil((firstThursday - date.getTime()) / 604800000)).padStart(2, '0')
const parsedDate = 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())
);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
newDate.setUTCDate(newDate.getUTCDate() + 4 - (newDate.getUTCDay() || 7));
// Get first day of year
const yearStart = new Date(Date.UTC(newDate.getUTCFullYear(), 0, 1));
// Calculate full weeks to nearest Thursday
const weekNo = Math.ceil(
((<number>(<unknown>newDate) - <number>(<unknown>yearStart)) / 86400000 + 1) / 7
);
return `${newDate.getUTCFullYear()}-W${weekNo < 10 ? '0' : ''}${weekNo}`;
}

/**
* Returns a date object for monday of given iso week string (\d\d\d\d-W\d\d)
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
import HTMLInputElementDateUtility from '../../../src/nodes/html-input-element/HTMLInputElementDateUtility.js';

describe('HTMLInputElementDateUtility', () => {
describe('dateToIsoWeek()', () => {
describe('dateIsoWeek()', () => {
it('Returns the ISO week number', () => {
expect(HTMLInputElementDateUtility.dateIsoWeek(new Date('2021-01-01'))).toBe('2020-W53');
expect(HTMLInputElementDateUtility.dateIsoWeek(new Date('2021-01-03'))).toBe('2020-W53');
Expand Down Expand Up @@ -35,7 +35,7 @@ describe('HTMLInputElementDateUtility', () => {
});
});

describe('IsoWeekToDate()', () => {
describe('isoWeekDate()', () => {
it('Returns the ISO week number', () => {
expect(HTMLInputElementDateUtility.isoWeekDate('2020-W53')).toEqual(
new Date('2020-12-28T00:00Z')
Expand Down

0 comments on commit 49d489d

Please sign in to comment.