Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

daysInMonth

Returns the number of days in a given month and year.

TypeScript
Copied!
1/**
2 * Returns the number of days in a given month and year.
3 *
4 * @param year - The full year (e.g. 2024)
5 * @param month - The month index (0 for January, 11 for December)
6 * @returns Number of days in the specified month.
7 */
8export function daysInMonth(year: number, month: number): number {
9  return new Date(year, month + 1, 0).getDate();
10}
  • Accurate Leap Year Handling

    Automatically accounts for leap years (e.g., 29 days in February 2024) without custom logic.

  • Concise and Efficient

    Uses a single Date object to calculate the result with minimal overhead and no loops or conditionals.

  • Zero-Based Month Input Compatibility

    Accepts a month index aligned with JavaScript’s Date API, reducing confusion and integration errors.

  • Pure and Deterministic

    Produces consistent results without relying on external state or side effects.

Tests | Examples

TypeScript
Copied!
1test('daysInMonth - February in leap year', () => {
2  expect(daysInMonth(2024, 1)).toBe(29); // February
3});
4
5test('daysInMonth - February in non-leap year', () => {
6  expect(daysInMonth(2023, 1)).toBe(28);
7});
8
9test('daysInMonth - April (30 days)', () => {
10  expect(daysInMonth(2023, 3)).toBe(30); // April
11});
12
13test('daysInMonth - July (31 days)', () => {
14  expect(daysInMonth(2023, 6)).toBe(31); // July
15});
16
17test('daysInMonth - December (31 days)', () => {
18  expect(daysInMonth(2023, 11)).toBe(31); // December
19});

Common Use Cases

  • Calendar Generation

    Determine how many day slots to display for a given month in UI components.

  • Date Validation

    Ensure a selected day number is valid for the target month (e.g., prevent Feb 30).

  • Date Range Calculations

    Calculate month boundaries for scheduling or iteration logic.

  • Financial/HR Apps

    Use in payroll systems or reports that depend on the number of days in a given month.

  • Dynamic Form Limits

    Set max limits in date-picker components based on selected year/month.

Codebase: Utilities -> Dates -> daysInMonth | Yevhen Klymentiev