I know this is late but I want to write more explanation if you guys let me!
Let's look at your examples line by line;
DateTime dtFromDate = Convert.ToDateTime("2015-01-01");
DateTime dtToDateDate = Convert.ToDateTime("2015-01-31");
With this conversation, your dtFromDate
will be 01/01/2015 00:00:00
and dtToDateDate
will be 31/01/2015 00:00:00
since you didn't write any time part, it will be assigned to midnight by default.
With dtToDateDate- dtFromDate
line, you will get a TimeSpan
which is exactly 30 day long as {30.00:00:00}
. Why? Well, simple;
+---------------------+---------------------+----------------+
| FirstDate | LastDate | Day Difference |
+---------------------+---------------------+----------------+
| 01/01/2015 00:00:00 | 01/01/2015 00:00:00 | 0 |
| 01/01/2015 00:00:00 | 02/01/2015 00:00:00 | 1 |
| 01/01/2015 00:00:00 | 03/01/2015 00:00:00 | 2 |
| ... | ... | ... |
| ... | ... | ... |
| 01/01/2015 00:00:00 | 31/01/2015 00:00:00 | 30 |
+---------------------+---------------------+----------------+
But how about DateTime.DaysInMonth(2015, 1)
?
DaysInMonth
method returns the number of days in the specified month and year. Since October has 31
days in Gregorian Calender, it returns 31
.
From wikipedia;
October is the tenth month of the year in the Julian and Gregorian
Calendars and one of seven months with a length of 31 days.
But this method doesn't use any DateTime
difference to calculate them. Here how it's implemented:
public static int DaysInMonth(int year, int month)
{
// IsLeapYear checks the year argument
int[] days = IsLeapYear(year)? DaysToMonth366: DaysToMonth365;
return days[month] - days[month - 1];
}
Since 2015
is not a leap year, days
array will be equal to DaysToMonth365
which is defined as;
private static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
And we provided month
parameter as 1
, this method returns
days[1] - days[0]
which is equal to
31 - 0
which is equal to 31
.