This formula reflects @RHSeeger's thought as a simple solution to get (in this example) the last day of the 3rd month (month of date in cell A1 + 4 with the first day of that month minus 1 day):
=DATE(YEAR(A1);MONTH(A1)+4;1)-1
Very precise, inclusive February's in leap years :)
// Use any date you want, for the purpose of this example we use 1980-08-03.
var myDate = new DateTime(1980,8,3);
var lastDayOfMonth = new DateTime(myDate.Year, myDate.Month, DateTime.DaysInMonth(myDate.Year, myDate.Month));
You can find the last day of the month by a single line of code:
int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
To get last day of a month in a specific calendar - and in an extension method -:
public static int DaysInMonthBy(this DateTime src, Calendar calendar)
{
var year = calendar.GetYear(src); // year of src in your calendar
var month = calendar.GetMonth(src); // month of src in your calendar
var lastDay = calendar.GetDaysInMonth(year, month); // days in month means last day of that month in your calendar
return lastDay;
}
From DateTimePicker:
First date:
DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);
Last date:
DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));
I don't know C# but, if it turns out there's not a convenient API way to get it, one of the ways you can do so is by following the logic:
today -> +1 month -> set day of month to 1 -> -1 day
Of course, that assumes you have date math of that type.
If you want the date, given a month and a year, this seems about right:
public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}
Substract a day from the first of next month:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);
Also, in case you need it to work for December too:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);
You can find the last date of any month by this code:
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
var DaysInMonth = DateTime.DaysInMonth(now.Year, now.Month);
var lastDay = new DateTime(now.Year, now.Month, DaysInMonth);
Source: Stackoverflow.com