Getting the First and Last day of the month with .NET C#
Ok so now you know how to get the last day of the month with SQL, but how can you get the first day or the last day of the month given a specific date? That problem is so simple with dot net and csharp! There is a convenience constructor for the DateTime object that can help us with it. This will even work with the computers local date time, or localizations.
Here is the DateTime constructor signature that we are going to use:
public DateTime( int year, int month, int day );
First day of the month
Here we take the date, and using the DateTime constructor (year, month, day). We can create a new DateTime object with the first day of the month.
Here is the simple wrapper method to get the first day of the month:
public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, 1);
}
Last day of the month
For the last day of the month we do basically the same thing as the first day of the month, except after we have that value we add 1 month, then subtract 1 day. Walla! We have the last day of the month with c#!
Here is the simple wrapper method to get the last day of the month:
public DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
{
DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}
2 Responses to “Getting the First and Last day of the month with .NET C#”
Comment from Mr Joka
Time March 21, 2007 at 3:51 am
very nice, exactly what i was looking for.
thanks
Write a comment
You need to login to post comments!
Comment from Solairaja
Time November 13, 2006 at 5:25 am
useful page