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);
}
Thứ Sáu, 7 tháng 1, 2011
New
Getting the First and Last day of the month with .NET C#
About ngoi sao co don
Templatesyard is a blogger resources site is a provider of high quality blogger template with premium looking layout and robust design. The main mission of templatesyard is to provide the best quality blogger templates.
Đăng ký:
Đăng Nhận xét (Atom)
Không có nhận xét nào:
Đăng nhận xét