我如何获得一个月的最后一天?
我怎样才能find在C#月的最后一天?
例如,如果我有date03/08/1980,我怎样才能得到第8个月的最后一天(在这个例子中是31)?
这个月的最后一天,你会得到这样的结果,返回31:
DateTime.DaysInMonth(1980, 08);
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
DateTime firstOfNextMonth = new DateTime(date.Year, date.Month, 1).AddMonths(1); DateTime lastOfThisMonth = firstOfNextMonth.AddDays(-1);
如果你想要的date ,给一个月和一年,这似乎是正确的:
public static DateTime GetLastDayOfMonth(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month)); }
从下个月的第一天开始抽出一天:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);
此外,如果你需要它也为十二月份工作:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);
您可以通过一行代码find月份的最后一天:
int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;
您可以通过此代码find任何月份的最后date:
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);
从DateTimePicker:
第一次约会:
DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);
最后date:
DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));
我不知道C#,但是,如果事实certificate没有一个方便的API来获取它,你可以这样做的方法之一是遵循逻辑:
today -> +1 month -> set day of month to 1 -> -1 day
当然,假设你有这种types的datemath。
要在特定日历中获取月份的最后一天,并使用扩展方法:
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; }