Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected month's last date in C#.net?

Tags:

c#

asp.net

I am using a drop down list for selecting the month in .aspx page. I have to get last date of the selected month in .aspx.cs page. (some months have 30 days and some have 31 days)

How can I do this?

like image 571
sriramjitendra Avatar asked Jan 20 '11 07:01

sriramjitendra


People also ask

How do you get the first and last day of the month?

Here, we use the EOMONTH function to go to the last day of the previous month. Then, we add 1 to get the first day of the current month. To perform the previous example with the EOMONTH function, we need to use the formula =EOMONTH(A2,-1)+1 in cell B2.

How do you check the date is last day of month in C#?

Actually it is accurate logic to get last day of a month in many languages including c# "new DateTime(1980,8,1). AddMonths(1). AddDays(-1);" as basic as this.


1 Answers

There's no need for custom calculations.

Use the System.DateTime.DaysInMonth(yearNum, monthNum) method to find out the number of days in any given month (which is also the last day).

It's as simple as:

//Get days in month 2 (Feb) of year 2011. Returns 28.
int daysInFeb2011 = System.DateTime.DaysInMonth(2011, 2); 

The MSDN documentation provides a more thorough and descriptive sample:

        const int July = 7;
        const int Feb = 2;

        // daysInJuly gets 31.
        int daysInJuly = System.DateTime.DaysInMonth(2001, July);

        // daysInFeb gets 28 because the year 1998 was not a leap year.
        int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);

        // daysInFebLeap gets 29 because the year 1996 was a leap year.
        int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);
like image 128
John K Avatar answered Sep 17 '22 12:09

John K