diff --git a/packages/date-picker/src/utils.test.ts b/packages/date-picker/src/utils.test.ts index 38adbb3f..1cb46f93 100644 --- a/packages/date-picker/src/utils.test.ts +++ b/packages/date-picker/src/utils.test.ts @@ -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); }); diff --git a/packages/date-picker/src/utils.ts b/packages/date-picker/src/utils.ts index 966cbb40..b4432303 100644 --- a/packages/date-picker/src/utils.ts +++ b/packages/date-picker/src/utils.ts @@ -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;