Skip to content

Commit

Permalink
Add + use getFirstDateFromMonth plus tests
Browse files Browse the repository at this point in the history
  • Loading branch information
acusti committed Apr 29, 2024
1 parent 7d017b0 commit 0f8e51e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
21 changes: 21 additions & 0 deletions packages/date-picker/src/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';

import {
getFirstDateFromMonth,
getMonthFromDate,
getMonthNameFromMonth,
getLastDateFromMonth,
Expand Down Expand Up @@ -69,6 +70,26 @@ describe('@acusti/date-picker', () => {
});
});

describe('getFirstDateFromMonth', () => {
it('returns the date of the first day for a post-unix epoch month', () => {
expect(
getFirstDateFromMonth(getMonthFromDate(new Date(2008, 2, 13))),
).toEqual(new Date(2008, 2, 1));
});

it('returns the correct date for a pre-unix epoch month', () => {
expect(
getFirstDateFromMonth(getMonthFromDate(new Date(1865, 5, 2))),
).toEqual(new Date(1865, 5, 1));
});

it('returns an invalid date if given NaN (e.g. if dealing with an Invalid Date)', () => {
expect(getFirstDateFromMonth(getMonthFromDate(INVALID_DATE))).toEqual(
INVALID_DATE,
);
});
});

describe('getLastDateFromMonth', () => {
it('returns the date of the last day for a post-unix epoch month', () => {
expect(
Expand Down
13 changes: 8 additions & 5 deletions packages/date-picker/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,13 @@ export const getMonthAbbreviationFromMonth = (month: number) => {
return monthName.substring(0, 3);
};

export const getFirstDateFromMonth = (month: number) => {
const monthIn12 = month < 0 ? (12 - Math.abs(month % 12)) % 12 : month % 12;
return new Date(getYearFromMonth(month), monthIn12, 1);
};

export const getLastDateFromMonth = (month: number) => {
const nextMonth = month + 1;
const nextMonthIn12 = nextMonth < 0 ? (12 - Math.abs(nextMonth % 12)) % 12 : nextMonth % 12;
const lastDate = new Date(getYearFromMonth(nextMonth), nextMonthIn12, 1);
lastDate.setDate(lastDate.getDate() - 1);
return lastDate;
const date = getFirstDateFromMonth(month + 1);
date.setDate(date.getDate() - 1);
return date;
};

0 comments on commit 0f8e51e

Please sign in to comment.