Finding the First and Last Day Of A Month in C#


If you've ever been tasked with finding records where they fall into a specific month, you can use the following method to calculate the first and last day of any month:


 

void GetMonthBoundaries(int month, int year, out DateTime firstDayOfMonth,
out DateTime lastDayOfMonth)
{
   // how to get the 1st day of the month? it's always day 1, so this is simple enough
   DateTime first = new DateTime(year, month, 1);
   // how do we get the last day of the month when months have
   // varying numbers of days?
   //
   // adding 1 month to "first" gives us the 1st day of the following month
   // then if we subtract one second from that date, we get a DateTime that
   // represents the last second of the last day of the desired month

   // example: if month = 2 and year = 2011, then
   // first = 2011-02-01 00:00:00
   // last = 2011-02-28 23:59:59
   DateTime last = first.AddMonths(1).AddSeconds(-1);
   // if you're not concerned with time of day in your DateTime values
   // and are only comparing days, then you can use the following line
   // instead to get the last day:
   //
   // DateTime last = first.AddMonths(1).AddDays(-1);
   // example: if month = 2 and year = 2011, then
   // first = 2011-02-01 00:00:00
   // last = 2011-02-28 00:00:00
   firstDayOfMonth = first;
   lastDayOfMonth = last;
}