C# Program to display the number of days in a month

The DateTime.DaysInMonth() method in C# is used to display the number of days in a specific month and year. This static method is particularly useful when working with calendar calculations or when you need to validate dates.

Syntax

Following is the syntax for using DateTime.DaysInMonth()

int days = DateTime.DaysInMonth(year, month);

Parameters

  • year: An integer representing the year (1 to 9999).

  • month: An integer representing the month (1 to 12).

Return Value

Returns an integer representing the number of days in the specified month and year.

Example

using System;

public class Demo {
    public static void Main() {
        Console.WriteLine("Today = {0}", DateTime.Today);
        int num_days = DateTime.DaysInMonth(2018, 8);
        Console.WriteLine("Days in August: " + num_days);
    }
}

The output of the above code is −

Today = 9/4/2018 12:00:00 AM
Days in August: 31

Using DaysInMonth with Different Months

using System;

public class MonthDays {
    public static void Main() {
        int year = 2024;
        string[] months = {"January", "February", "March", "April"};
        
        for (int month = 1; month <= 4; month++) {
            int days = DateTime.DaysInMonth(year, month);
            Console.WriteLine("{0} {1} has {2} days", months[month-1], year, days);
        }
    }
}

The output of the above code is −

January 2024 has 31 days
February 2024 has 29 days
March 2024 has 31 days
April 2024 has 30 days

Handling Leap Years

The DaysInMonth() method automatically handles leap years. February will return 29 days for leap years and 28 days for regular years −

using System;

public class LeapYearDemo {
    public static void Main() {
        int[] years = {2020, 2021, 2024, 2025};
        
        foreach (int year in years) {
            int febDays = DateTime.DaysInMonth(year, 2);
            string leapStatus = DateTime.IsLeapYear(year) ? "Leap Year" : "Regular Year";
            Console.WriteLine("February {0}: {1} days ({2})", year, febDays, leapStatus);
        }
    }
}

The output of the above code is −

February 2020: 29 days (Leap Year)
February 2021: 28 days (Regular Year)
February 2024: 29 days (Leap Year)
February 2025: 28 days (Regular Year)

Conclusion

The DateTime.DaysInMonth() method provides a reliable way to determine the number of days in any month and year. It automatically handles leap years and returns the correct number of days for February, making it essential for date calculations and calendar applications.

Updated on: 2026-03-17T07:04:35+05:30

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements