Skip to content

Commit

Permalink
YearWeek adjustments
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarfgq authored and geoperez committed Jan 5, 2024
1 parent 0375ae1 commit fa213ad
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
32 changes: 29 additions & 3 deletions src/dateRange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,35 @@ export class YearMonth extends DateRange implements IYearMonthDateRange {
}
}

export const getWeekNumber = (date: Date) => {
const onejan = new Date(date.getFullYear(), 0, 1);
return Math.ceil(((date.getTime() - onejan.getTime()) / 86400000 + onejan.getDay() + 1) / 7);
const getStartOfWeek = (date: Date) => {
const startOfWeek = new Date(date);
const diffDays = startOfWeek.getDay();
startOfWeek.setDate(startOfWeek.getDate() - diffDays);
startOfWeek.setHours(0, 0, 0, 0);
return startOfWeek;
};

const areDatesInSameWeek = (date1: Date, date2: Date) => {
const startOfWeek1 = getStartOfWeek(date1);
const startOfWeek2 = getStartOfWeek(date2);
return startOfWeek1.getTime() === startOfWeek2.getTime();
};

export const getWeekNumber = (date: Date): number => {
const jan1st = new Date(date.getFullYear(), 0, 1);
const daysFromJan1UntilDate = Math.floor((date.getTime() - jan1st.getTime()) / (24 * 60 * 60 * 1000));
const offsetFromJan1ToSundaySameWeek = -(jan1st.getDay() % 7) % 7;
const weeksRaw = (daysFromJan1UntilDate + offsetFromJan1ToSundaySameWeek) / 7;

const weekOfDate =
(weeksRaw >= 0 ? Math.floor(weeksRaw) : Math.ceil(weeksRaw)) + (daysFromJan1UntilDate !== 365 ? 1 : 0);

const lastDayOfPreviousYear = new Date(date.getFullYear() - 1, 11, 31);

if (weekOfDate === 1 && areDatesInSameWeek(lastDayOfPreviousYear, date))
return getWeekNumber(lastDayOfPreviousYear);

return weekOfDate;
};

export const getWeekOfYear = (): number => getWeekNumber(new Date());
Expand Down
12 changes: 6 additions & 6 deletions src/dateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ const formatWeekDaysRange = (start: Date, end: Date) =>

export const getWeekDaysRange = (week: number, year?: number) => {
year = year ?? new Date().getFullYear();
const firstDayOfYear = new Date(year, 0, 1);

let pivotDay = 1 + (week - 1) * 7 - firstDayOfYear.getDay();
const jan1st = new Date(year, 0, 1);
const offsetToFirstSunday = (7 - jan1st.getDay()) % 7;
const weekStart = new Date(jan1st);
weekStart.setDate(jan1st.getDate() + offsetToFirstSunday + (week - 1) * 7);

if (firstDayOfYear.getDay() > 4) pivotDay += 7;

const weekStart = new Date(year, 0, pivotDay);
const weekEnd = new Date(year, 0, pivotDay + 6);
const weekEnd = new Date(weekStart);
weekEnd.setDate(weekStart.getDate() + 6);

return formatWeekDaysRange(weekStart, weekEnd);
};
Expand Down

0 comments on commit fa213ad

Please sign in to comment.