Wednesday, August 18, 2010

DateTime Extension Methods for first and last days of the month

I have seen several articles on how to derive the first and last day of the month from a given date. This method uses .Net 4.0 extension methods, which is a more elegant solution.



using System;

namespace MRMPortal.Service.Extensions
{
public static class DateTimeExtensionMethods
{
public static DateTime FirstDayOfMonth(this DateTime value)
{
return new DateTime(value.Year, value.Month, 1);
}

public static DateTime LastDayOfMonth(this DateTime value)
{
return new DateTime(value.Year, value.Month, 1).AddMonths(1).AddDays(-1);
}
}
}

No comments:

Post a Comment