A Few Date Methods

Posted by Ryan Baxter Tue, 06 May 2008 18:45:00 GMT

An ASP.NET project of mine recently required the calculation of the start and end date of the current date’s previous month. This was more difficult putting into words than code. It did, however, get me thinking about other common date routines.

public static DateTime FirstDayOfPreviousMonth
{
    get
    {
        return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
    }    
}

public static DateTime LastDayOfPreviousMonth
{
    get
    {
        return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);
    }
}

Being preemptive, I decided to include a few methods for determining the start and end date of the current date’s fiscal quarter. I started by calculating the current date’s quarter. This was accomplished with just a little division.

public static int CurrentQuarter
{
    get
    {
        return (DateTime.Now.Month + 2) / 3;
    }
}

Finding the start and end dates of the current quarter was harder, but could still be expressed in a single line of code (or two).

public static DateTime FirstDayOfCurrentQuarter
{
    get
    {
        return new DateTime(DateTime.Now.Year, 1 + ((CurrentQuarter - 1) * 3), 1);
    }
}

public static DateTime LastDayOfCurrentQuarter
{
    get
    {
        int lastMonthOfCurrentQuarter = 3 + ((CurrentQuarter - 1) * 3);

        return new DateTime(DateTime.Now.Year, lastMonthOfCurrentQuarter, DateTime.DaysInMonth(DateTime.Now.Year, lastMonthOfCurrentQuarter));
    }
}

I’d like to extend this collection to include other common date routines. Feel free to post your date methods as comments if you’d like to share.

*The methods I’ve created for calculating the current quarter’s start and end dates assume the fiscal year starts on January 1st. This may not be suitable for your needs.