Later Today: ASP.NET Tutorial 2: Introduction to C#

(C#) DateTimes: Finding the last day of a month

Prerequisites: Good understanding of the DateTime data type.

Since we know that all months have at least one day, setting an existing DateTime to the first day of a month is a cinch… but finding the last day of a month is a wee bit more complicated since months tend to have a variable number of days from year to year.

Fortunately, there is a relatively simple (if roundabout) way to calculate the last day in a month.

v Scenario

Let’s say we need to calculate the DateTime for the very last day of February, 2077. We don’t know if it’s a leap year or what, so we need to be able to programatically calculate what the last day of that month is.

v Logic

  1. Using any valid DateTime as our starting point, set our DateTime to the first day of the month, with DateTime().
  2. Add exactly one month to the DateTime to get the first day of the next month, using DateTime.AddMonths().
  3. Finally, subtract exactly one day from the DateTime, using DateTime.AddDays().
  4. The DateTime will now be set to last day of the previous month (which was our original month).

v Example 1 – Practical Example

This example demonstrates the process in simple, practical terms.

C#:
//Create a valid DateTime variable to use as our starting point (the exact day doesn't matter)
DateTime dt = Convert.ToDateTime("2/13/2076");
dt = new DateTime(dt.Year, dt.Month, 1); //Select the first day of the month by using the DateTime class
dt = dt.AddMonths(1); //Add one month to our adjusted DateTime
dt = dt.AddDays(-1); //Subtract one day from our adjusted DateTime
//Our DateTime variable is now set to the last day of February 2077, which happens to be 2/29/2076.

v Example 2 – Method

This example demonstrates the logic in within a portable, reusable method.

C#:
///<summary>This function will find the last day of the month for the DateTime passed into it. </summary>
///<param name="dt">A DateTime of the month/year for which you need to find the last day. </param>
///<return> A DateTime of the last day of the month for the month/year entered. </return>
public DateTime LastDayofMonth(DateTime dt)
{
    //Select the first day of the month by using the DateTime class
    dt = new DateTime(dt.Year, dt.Month, 1);
    //Add one month to our adjusted DateTime
    dt = dt.AddMonths(1);
    //Subtract one day from our adjusted DateTime
    dt = dt.AddDays(-1);
    //Return the DateTime, now set to the last day of the month
    return dt;
}

No Comments

Post a Comment

You must be logged in to post a comment.

RSS Twitter LinkedIn Facebook
Doing neato things with JavaScript, please wait...