Menu ▼

Posted By :
Total Views : 2292

Get total number of days in a given month/date in C#

C# DateTime method DateTime.DaysInMonth(year, month) will give you the number of days in the given month of the year. you have to pass the year and month of the given date to the method. Below example shows you how to use the DateTime.DaysInMonth method to get the number of days in a give date / month.

number of days in a month

CS Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Globalization;

namespace WebApplication1
    public partial class _Default : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)


        protected void btnGetDays_Click(object sender, EventArgs e)
            DateTime dt = DateTime.ParseExact(txtDate.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
            int numberOfDays = DateTime.DaysInMonth(dt.Year, dt.Month);
            lblMessage.Text = "Number of days in the month " + dt.ToString("MMM-yyyy") + " is: <span style='color:red;'>" + numberOfDays + "</span>";


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head id="Head1" runat="server">
    <form id="form1" runat="server">
        Date :
        <asp:TextBox ID="txtDate" runat="server" Text="11/23/2015"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnGetDays" runat="server" Text="Get Number Of Days" OnClick="btnGetDays_Click" />
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Style="color: Green; font-weight: bold;
            font-size: 14px;"></asp:Label>

comments powered by Disqus