Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting number of days for a specific month

Tags:

how could i programmatically detect, how many days are there for a particular month & year.

like image 695
Thomas Avatar asked Feb 15 '11 10:02

Thomas


People also ask

How do you calculate the number of days in a month?

How to Convert Months to Days. To convert a month measurement to a day measurement, multiply the time by the conversion ratio. The time in days is equal to the months multiplied by 30.436875.

How do I calculate the number of days in a month in Excel?

1. Select a blank cell you will place the counting result into, and type the formula =DAY(DATE(YEAR(B1),MONTH(B1)+1,)) (B1 is the cell with the given date) into it, and press the Enter key. And then you will get the total number of days in the specified month based on a given date.

How do you list all days as date in a specified month in Excel?

Now you need to change the result cell to date format with clicking Home > Number Format box > Short Date. See screenshot. 4. Keep selecting the result cell, then drag the Fill Handle down to list all days as date of this specified month.


2 Answers

It's already there:

DateTime.DaysInMonth(int year, int month); 

should do it.

like image 76
Zano Avatar answered Oct 12 '22 10:10

Zano


Something like this should do what you want:

static int GetDaysInMonth(int year, int month) {     DateTime dt1 = new DateTime(year, month, 1);     DateTime dt2 = dt1.AddMonths(1);     TimeSpan ts = dt2 - dt1;     return (int)ts.TotalDays; } 

You get the first day of the month, add one month and count the days in between.

like image 29
Paolo Tedesco Avatar answered Oct 12 '22 08:10

Paolo Tedesco