4

I have a method which passes two parameters Month and year

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

public static string MonthDates(string MonthName,string YearName)
{
     return days;
}

How to get the days for particular month and year?

user405477
  • 51
  • 1
  • 4
  • If the question is about parsing the string, see this: [How to parse a month name (string) to an integer for comparison in C#?](http://stackoverflow.com/questions/258793/how-to-parse-a-month-name-string-to-an-integer-for-comparison-in-c) – Kobi Jul 29 '10 at 09:35

4 Answers4

12

do you mean the number of days in a month?

System.DateTime.DaysInMonth(int year, int month)
Andrew Bullock
  • 36,616
  • 34
  • 155
  • 231
5

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);
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • i am passng a string as a parameter – user405477 Jul 29 '10 at 09:31
  • @ravidotnet - Can you please edit the question? Is the question about parsing these string, turning them into number? This is something you want to do at the first stage after reading the data, you don't want to pass strings around. – Kobi Jul 29 '10 at 09:33
  • i will pass as MOnthDates(janauary,2010) which should returns number of days as 1,2,3,........31 days – user405477 Jul 29 '10 at 09:37
2
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

loxxy
  • 12,990
  • 2
  • 25
  • 56
1

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.

Anindya Chatterjee
  • 5,824
  • 13
  • 58
  • 82