Getting the First and Last day of the month with .NET C# - Vì tương lai phía trước

Latest

Thứ Sáu, 7 tháng 1, 2011

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);
}

Không có nhận xét nào:

Đăng nhận xét