I'm writing a tidgy little app that will take a load of data about our press releases out of one of our databases and turn into flat HTML files. It needs to write separate files for years and months - years are easy as it's just a for loop, and months are also a for loop, but I need to know the end date for each month so I can create the appropriate SQL query. I'd written a switch block to calculate the last day of the month:
for (int i = 1; i < 13; i++)
{
DateTime startDate = new DateTime(int.Parse(year), i, 1, 0, 0, 0);
DateTime endDate;
switch (i)
{
case 9, 4, 6, 11:
endDate = new DateTime(int.Parse(year), i, 30, 23, 59, 59);
break;
case 2:
endDate = new DateTime(int.Parse(year), i, 28, 23, 59, 59);
// TODO: Leap years
break;
default:
endDate = new DateTime(int.Parse(year), i, 31, 23, 59, 59);
break;
}
}
But further down in my code, I was doing something else with the DateTime class and I spotted it has a DaysInMonth function. You give it a year and a month (both ints), and it calculates the number of days in the month for you, and deals with the leap years that I hadn't got round to doing. Which means I can collapse my for down to:
for (int i = 1; i < 13; i++)
{
DateTime startDate = new DateTime(int.Parse(year), i, 1, 0, 0, 0);
DateTime endDate = new DateTime(int.Parse(year), DateTime.DaysInMonth(int.Parse(year), i), 30, 23, 59, 59);
}
Smaller code for the win!
EDIT: I just looked DaysInMonth up on MSDN and I'm surprised to discover it's been in the Framework since .NET 1.0!
EDIT: I just looked DaysInMonth up on MSDN and I'm surprised to discover it's been in the Framework since .NET 1.0!
1 comment:
Hi,
An easier (IMHO) way would be just adding one month to the start date and then subtract one day and let the DateTime class calculate the last day of the month.
Something like:
DateTime startDate = new DateTime(int.Parse(year), i, 1, 0, 0, 0);
DateTime endDate = startDate.AddMonths(1).AddDays(-1);
Cheers,
Caio Proiete
Post a Comment