Search

Thursday, May 1, 2014
0 comments

How to find last day of month in ASP.NET C#

1:17 AMThursday, May 1, 2014

Introduction

If you want to get last day of this month , use DateTime structure with AddMonths( ) method. using this method you can get first day of next month. Now, create a new instance of DateTime structure with some parameter like DateTime(Int32, Int32, Int32). This parameterized method Initializes a new instance of the DateTime structure to the specified year, month, and day. Here you can pass integer 1 in day field. Now, you can delete 1 day from current DateTime object using AddDays (-1) method. Now, your object will return last day of current month.

<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
         runat="server"
         onclick="Button1_Click"
         Text="Click"
         BackColor="#99CCFF" />  
    </div>
        <asp:Label ID="Label1"
         runat="server"
         Text="Label"
         BackColor="Yellow"></asp:Label>
    </form>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
        {        
            DateTime today = DateTime.Today;          
            DateTime tempDate = today.AddMonths(1);
            DateTime tempDate3 = new DateTime(tempDate.Year, tempDate.Month, 1);
            DateTime Monthlastday = tempDate3.AddDays(-1);
            Label1.Text = "Today : " + today.ToLongDateString();
            Label1.Text += "<br /><br />month last day= ";
            Label1.Text += Monthlastday.ToLongDateString();

        }

Code generate the following output


Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top