calendar
months
leap year
days in month
year calculation

Number of days in particular month of particular year?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Getting the number of days in a given month looks easy until leap years enter the picture. This logic appears in billing, booking, reporting, and validation code, and small mistakes around February or century years can produce surprisingly expensive bugs.

The safest approach is to rely on a standard library when possible. If you need to implement the logic yourself, make sure you are using the Gregorian leap-year rules correctly.

The Leap-Year Rule

For the Gregorian calendar, February changes depending on whether the year is a leap year.

A year is a leap year if:

  • it is divisible by 4
  • except years divisible by 100
  • except those divisible by 400, which are leap years again

So:

  • '2024 is a leap year'
  • '1900 is not a leap year'
  • '2000 is a leap year'

That is the part people most often oversimplify.

Manual Implementation in Python

A clear hand-written implementation is useful for understanding and for small standalone logic.

python
1def is_leap_year(year: int) -> bool:
2    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
3
4
5def days_in_month(year: int, month: int) -> int:
6    if month < 1 or month > 12:
7        raise ValueError("month must be between 1 and 12")
8
9    if month == 2:
10        return 29 if is_leap_year(year) else 28
11
12    if month in (4, 6, 9, 11):
13        return 30
14
15    return 31
16
17
18print(days_in_month(2024, 2))
19print(days_in_month(2025, 2))
20print(days_in_month(2025, 11))

This function is explicit, testable, and easy to review.

Use Standard Libraries in Real Code

In production code, standard library date APIs are usually better because they avoid duplicated calendar logic.

Python example:

python
1import calendar
2
3_, count = calendar.monthrange(2032, 2)
4print(count)

Java example:

java
1import java.time.YearMonth;
2
3public class Main {
4    public static void main(String[] args) {
5        int days = YearMonth.of(2032, 2).lengthOfMonth();
6        System.out.println(days);
7    }
8}

Swift example:

swift
1import Foundation
2
3func dayCount(year: Int, month: Int) -> Int? {
4    var comps = DateComponents()
5    comps.calendar = Calendar(identifier: .gregorian)
6    comps.year = year
7    comps.month = month
8    comps.day = 1
9
10    guard let date = comps.date,
11          let range = comps.calendar?.range(of: .day, in: .month, for: date) else {
12        return nil
13    }
14
15    return range.count
16}
17
18print(dayCount(year: 2032, month: 2) ?? -1)

These library-based solutions reduce the chance of edge-case mistakes and usually communicate intent better.

Input Validation Matters

The calendar rule is only part of the problem. Real bugs also come from bad inputs:

  • month 0
  • month 13
  • text that was parsed loosely into an invalid integer
  • timezone conversions mixed into what should be a pure month-length lookup

If the values come from timestamps, convert to the correct local date first and then ask for the month length. Otherwise you can accidentally shift into a different month at a timezone boundary.

Testing the Edge Cases

At minimum, test the leap-year edges and invalid month values.

python
1cases = [
2    (2024, 2, 29),
3    (2025, 2, 28),
4    (1900, 2, 28),
5    (2000, 2, 29),
6    (2026, 4, 30),
7    (2026, 5, 31),
8]
9
10for y, m, expected in cases:
11    got = days_in_month(y, m)
12    assert got == expected, (y, m, expected, got)

These few cases catch most logical regressions immediately.

Common Pitfalls

A common mistake is treating “divisible by 4” as the whole leap-year rule and ignoring the century exceptions.

Another issue is returning a default value such as 0 for invalid months instead of failing clearly. Silent fallback values make bad input harder to diagnose.

Developers also sometimes reimplement this logic in every service even though their language already provides a standard library answer.

Finally, avoid mixing timezone conversion, timestamp parsing, and month-length calculation in one opaque function. Keep the calendar logic simple and focused.

Summary

  • Month length depends on the Gregorian leap-year rule, especially for February.
  • The correct leap-year rule includes the 100 and 400 year exceptions.
  • Standard library APIs are usually the safest production solution.
  • Validate month input before calculating the result.
  • Add a few leap-year edge cases to tests so this logic stays correct.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.