关于c#:我如何获得一个月的最后一天?

How do I get the last day of a month?

我怎样才能在C中找到这个月的最后一天?

例如,如果我的日期是1980年8月3日,我如何获得8月的最后一天(在本例中是31天)?


每月的最后一天,您会得到这样的结果,返回31:

1
DateTime.DaysInMonth(1980, 08);


1
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);


1
2
DateTime firstOfNextMonth = new DateTime(date.Year, date.Month, 1).AddMonths(1);
DateTime lastOfThisMonth = firstOfNextMonth.AddDays(-1);


如果你想要一个月一年的日期,这似乎是正确的:

1
2
3
4
public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
    return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}

从下个月的第一天减去一天:

1
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);

此外,如果您还需要它在12月工作:

1
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);

您可以通过一行代码找到月份的最后一天:

1
int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;


您可以通过此代码找到任何月份的最后一个日期:

1
2
3
4
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:

< >第一次约会:

1
DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);

最后日期:

1
DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));

要获取特定日历和扩展方法中月份的最后一天,请执行以下操作:

1
2
3
4
5
6
7
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;
}

1
2
3
// 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));


我不知道C,但是,如果事实证明没有一种方便的API方法来获取它,那么您可以通过以下逻辑来实现这一点:

1
today -> +1 month -> set day of month to 1 -> -1 day

当然,这假设您有这种类型的日期数学。