首页 文章

我怎样才能获得一个月的最后一天?

提问于
浏览
240

如何在C#中找到该月的最后一天?

例如,如果我的日期是03/08/1980,那么如何获得第8个月的最后一天(在这种情况下为31)?

11 回答

  • 1

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

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

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

    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);
    
  • 9

    来自 DateTimePicker:

    第一次约会:

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

    上次日期:

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

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

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

    当然,假设您有该类型的日期数学 .

  • 6

    要获取特定日历中的一个月的最后一天 - 以及扩展方法 - :

    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;
    }
    
  • 72
    // 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));
    
  • 148

    这个月的最后一天,你得到这样的,返回31:

    DateTime.DaysInMonth(1980, 08);
    
  • 1
    var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
    
  • 492
    DateTime firstOfNextMonth = new DateTime(date.Year, date.Month, 1).AddMonths(1);
    DateTime lastOfThisMonth = firstOfNextMonth.AddDays(-1);
    
  • 1

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

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

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

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

    此外,如果您需要它也适用于12月:

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

相关问题