how to get the days for particular month and year

后端 未结 4 754
天涯浪人
天涯浪人 2021-01-13 17:37

I have a method which passes two parameters Month and year

i will call this Method like this : MonthDates(January,2010)

public static string MonthDa         


        
相关标签:
4条回答
  • 2021-01-13 17:58

    do you mean the number of days in a month?

    System.DateTime.DaysInMonth(int year, int month)
    
    0 讨论(0)
  • 2021-01-13 18:10
    System.DateTime.Now.Month
    System.DateTime.Now.Year
    System.DateTime.Now.Day
    

    And so on.........You have lots of things you can get from DateTime.Now

    0 讨论(0)
  • 2021-01-13 18:10

    instead of string try to declare an enum like the following

    public enum Month
    {
       January = 1,
       February,
       March,
       .... so on
    }
    

    then pass it to the function of yours and use the followings in your function

    return System.DateTime.DaysInMonth(year, month);
    

    Instead of string try to use integer, as it will reduce the overhead of parsing strings.

    0 讨论(0)
  • 2021-01-13 18:15

    If you want all days as a collection of DateTime:

    public static IEnumerable<DateTime> daysInMonth(int year, int month)
    {
        DateTime day = new DateTime(year, month, 1);
        while (day.Month == month)
        {
            yield return day;
            day = day.AddDays(1);
        }
    }
    

    The use is:

    IEnumerable<DateTime> days = daysInMonth(2010, 07);
    
    0 讨论(0)
提交回复
热议问题