c# - How to get the number of days in a given month

Get days in month
DateTime.DaysInMonth() method return the number of days in the specified month and year. this method exists in System namespace. DateTime.DaysInMonth(year, month) method require to pass two parameters named 'year' and 'month'. the 'year' parameter value data type is System.Int32 which represent the specified year. the 'month' parameter value data type also System.int32 which represent a month number ranging from 1 to 12.

this method return value data type is System.Int32 which represent the number of days in specified month for the specified year. this is very useful method to get the number of days in February month in a specified year which depend on leap year.

the following asp.net c# example code demonstrate us how can we get days (count number of days) in a specified month and year programmatically at run time in an asp.net application.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
            Button1.Font.Bold = true;
            Button1.ForeColor = System.Drawing.Color.IndianRed;
            Button1.Text = "Get DaysInMonth";
            Label1.Font.Size = FontUnit.Larger;
            Label1.ForeColor = System.Drawing.Color.IndianRed;
            Label1.Font.Bold = true;
            Label1.Font.Italic = true;
    protected void Button1_Click(object sender, System.EventArgs e) {
        int year = DateTime.Now.Year;
        int month = DateTime.Now.Month;

        string dyasInMonth = DateTime.DaysInMonth(year,month).ToString();

        Label1.Text = "Today " + DateTime.Now.ToLongDateString();
        Label1.Text += "<br />Days In Month?: " + dyasInMonth;

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to get days in month (DaysInMonth) in asp.net</title>
    <form id="form1" runat="server">
        <h2 style="color:Teal">asp.net date time example: DaysInMonth</h2>
        <br /><br />
More c# examples