Skip to content

Commit

Permalink
Add asUTC option to getMonthFromDate util
Browse files Browse the repository at this point in the history
plus new tests to verify the behavior
  • Loading branch information
acusti committed May 8, 2024
1 parent fcd9711 commit 4ca71cb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
10 changes: 10 additions & 0 deletions packages/date-picker/src/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ describe('@acusti/date-picker', () => {
expect(getMonthFromDate(new Date(1968, 3, 30))).toBe(-21); // april 30, 1968
});

it('returns the correct month digit based on UTC time if asUTC is true', () => {
const date = new Date('1970-01-01T00:00:00.000Z');
expect(getMonthFromDate(date, true)).toBe(0);
// if test is run in a timezone behind UTC, ommitting asUTC returns -1
// if not, the month should be the same with or without asUTC flag
expect(getMonthFromDate(date)).toBe(
date.getTimezoneOffset() >= 60 ? -1 : 0,
);
});

it('returns NaN for an Invalid Date', () => {
expect(getMonthFromDate(INVALID_DATE)).toBe(NaN);
});
Expand Down
9 changes: 6 additions & 3 deletions packages/date-picker/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@ const MONTH_NAMES = [
'December',
];

const getYearFromDate = (date: Date) => date.getFullYear() - START_YEAR;
const getYearFromDate = (date: Date, asUTC?: boolean) =>
(asUTC ? date.getUTCFullYear() : date.getFullYear()) - START_YEAR;

export const getMonthFromDate = (date: Date) =>
date.getMonth() + (getYearFromDate(date) * 12); // prettier-ignore
export const getMonthFromDate = (date: Date, asUTC?: boolean) => {
const yearAsMonths = getYearFromDate(date, asUTC) * 12;
return yearAsMonths + (asUTC ? date.getUTCMonth() : date.getMonth());
};

export const getYearFromMonth = (month: number) => Math.floor(month / 12) + START_YEAR;

Expand Down

0 comments on commit 4ca71cb

Please sign in to comment.