代码之家  ›  专栏  ›  技术社区  ›  Irwin

你觉得这个月的最后一天怎么样?[副本]

  •  82
  • Irwin  · 技术社区  · 14 年前


    How to get the last day of a month?

    到目前为止,我有这个:

    DateTime createDate = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
    

    有更好的办法吗?

    4 回复  |  直到 8 年前
        1
  •  230
  •   Jon Skeet    14 年前

    用一下怎么样 DaysInMonth :

    DateTime createDate = new DateTime (year, month,
                                        DateTime.DaysInMonth(year, month));
    

    (自我提醒-一定要让这件事变得简单 Noda Time

        2
  •  23
  •   Øyvind Bråthen    14 年前

    你可以用这个方法 DateTime.DaysInMonth(year,month)

        3
  •  7
  •   Donald    14 年前

    下面是我在CodePlex上的一个有用的DateTime扩展库中找到的一个优雅方法:

    http://datetimeextensions.codeplex.com/

    下面是一些示例代码:

        public static DateTime First(this DateTime current)
        {
            DateTime first = current.AddDays(1 - current.Day);
            return first;
        }
    
        public static DateTime First(this DateTime current, DayOfWeek dayOfWeek)
        {
            DateTime first = current.First();
    
            if (first.DayOfWeek != dayOfWeek)
            {
                first = first.Next(dayOfWeek);
            }
    
            return first;
        }
    
        public static DateTime Last(this DateTime current)
        {
            int daysInMonth = DateTime.DaysInMonth(current.Year, current.Month);
    
            DateTime last = current.First().AddDays(daysInMonth - 1);
            return last;
        }
    

    它还有一些其他有用的扩展,可能对您有帮助。

        4
  •  2
  •   Charles Bretana    8 年前

    var anyDt = DateTime.Now;
    var lastDayOfMonth = anyDt.AddMonths(1).AddDays(anyDt.AddMonths(1).Day).Date;
    

    或:

    var anyDt = DateTime.Now;
    var lastDayOfMonth = anyDt.AddDays(1-anyDt.Day).AddMonths(1).AddDays(-1).Date; 
    

    或者作为一种方法:

    DateTime LastDayInMonth(DateTime anyDt)
       { return anyDt.AddMonths(1).AddDays(anyDt.AddMonths(1).Day).Date; }
    

    或者作为扩展方法:

    DateTime LastDayInMonth(DateTime this anyDt)
       { return anyDt.AddMonths(1).AddDays(anyDt.AddMonths(1).Day).Date; }