如何在C#.net中选择月份的最后一个日期?

时间:2022-08-25 10:56:26

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)

我正在使用下拉列表在.aspx页面中选择月份。我必须在.aspx.cs页面中获取所选月份的最后日期。 (有些月份有30天,有些月份有31天)

How can I do this?

我怎样才能做到这一点?

1 个解决方案

#1


24  

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).

使用System.DateTime.DaysInMonth(yearNum,monthNum)方法查找任何给定月份(也是最后一天)的天数。

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:

MSDN文档提供了更全面和描述性的示例:

        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);

#1


24  

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).

使用System.DateTime.DaysInMonth(yearNum,monthNum)方法查找任何给定月份(也是最后一天)的天数。

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:

MSDN文档提供了更全面和描述性的示例:

        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);