【问题标题】:Get the previous month's first and last day dates in c#在c#中获取上个月的第一天和最后一天的日期
【发布时间】:2010-10-10 03:45:43
【问题描述】:

我想不出一个简单的一两个班轮可以得到前几个月的第一天和最后一天。

我正在对一个调查 Web 应用程序进行 LINQ 化,他们在其中添加了一个新要求。

调查必须包括上个月的所有服务请求。所以如果是 4 月 15 日,我需要所有 Marches 请求 ID。

var RequestIds = (from r in rdc.request 
                  where r.dteCreated >= LastMonthsFirstDate && 
                  r.dteCreated <= LastMonthsLastDate 
                  select r.intRequestId);

如果没有开关,我就无法轻易想到日期。除非我是盲目的并且忽略了这样做的内部方法。

【问题讨论】:

    标签: c# .net datetime date


    【解决方案1】:

    我过去这样做的方式是首先获得本月的第一天

    dFirstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
    

    然后减去一天得到上个月的月底

    dLastDayOfLastMonth = dFirstDayOfThisMonth.AddDays (-1);
    

    然后减去一个月得到上个月的第一天

    dFirstDayOfLastMonth = dFirstDayOfThisMonth.AddMonths(-1);
    

    【讨论】:

    • +1,但为了迂腐,您最好评估一次 DateTime.Today 并将其存储在局部变量中。如果您的代码在午夜前一纳秒开始执行,则对 DateTime.Today 的两次连续调用可能会返回不同的值。
    • 是的,谢谢,大家都指正了,连书呆子都修正了。
    • 好吧,让编译器对你不那么迂腐:)
    • 赞成比较 return date.AddDays(-(date.Day-1))return new DateTime(date.Year, date.Month, 1); 并且第一次超过 2000 次迭代的性能更好(923 毫秒更新与 809 毫秒返回相同的对象)
    【解决方案2】:
    DateTime LastMonthLastDate = DateTime.Today.AddDays(0 - DateTime.Today.Day);
    DateTime LastMonthFirstDate = LastMonthLastDate.AddDays(1 - LastMonthLastDate.Day);
    

    【讨论】:

    • DateTime.Today.Days -> 'System.DateTime' 不包含 'Days' 的定义...
    【解决方案3】:
    var today = DateTime.Today;
    var month = new DateTime(today.Year, today.Month, 1);       
    var first = month.AddMonths(-1);
    var last = month.AddDays(-1);
    

    如果你真的需要一两行的话,把它们串联起来。

    【讨论】:

    • IIRC DateTime.Today 是一个非常昂贵的调用,因此您最好先将值存储在变量中。无论如何都是好答案:)
    • @andleer 这是一个不错的库,就像你提到的 fluentdatetime.codeplex.com
    • @MatthewLock,链接好像坏了。
    • 我只想指出,如果条目是使用完整的日期时间存储的,则此查询可能无法检索到该月最后一天凌晨 12:00 之后开始的任何条目。您可以通过将最后一行更改为 var last = month.AddTicks(-1); 来解决这个问题
    【解决方案4】:
    DateTime now = DateTime.Now;
    int prevMonth = now.AddMonths(-1).Month;
    int year = now.AddMonths(-1).Year;
    int daysInPrevMonth = DateTime.DaysInMonth(year, prevMonth);
    DateTime firstDayPrevMonth = new DateTime(year, prevMonth, 1);
    DateTime lastDayPrevMonth = new DateTime(year, prevMonth, daysInPrevMonth);
    Console.WriteLine("{0} {1}", firstDayPrevMonth.ToShortDateString(),
      lastDayPrevMonth.ToShortDateString());
    

    【讨论】:

    • 如果 DateTime.Now 在第一次调用时产生 2009-01-31 而在第二次调用时产生 2009-02-01 怎么办?
    【解决方案5】:

    如果您的日期时间有可能不是严格的日历日期,您应该考虑使用结束日期排除比较... 这将防止您错过在 1 月 31 日创建的任何请求。

    DateTime now = DateTime.Now;
    DateTime thisMonth = new DateTime(now.Year, now.Month, 1);
    DateTime lastMonth = thisMonth.AddMonths(-1);
    
    var RequestIds = rdc.request
      .Where(r => lastMonth <= r.dteCreated)
      .Where(r => r.dteCreated < thisMonth)
      .Select(r => r.intRequestId);
    

    【讨论】:

      【解决方案6】:

      一种使用扩展方法的方法:

      class Program
      {
          static void Main(string[] args)
          {
              DateTime t = DateTime.Now;
      
              DateTime p = t.PreviousMonthFirstDay();
              Console.WriteLine( p.ToShortDateString() );
      
              p = t.PreviousMonthLastDay();
              Console.WriteLine( p.ToShortDateString() );
      
      
              Console.ReadKey();
          }
      }
      
      
      public static class Helpers
      {
          public static DateTime PreviousMonthFirstDay( this DateTime currentDate )
          {
              DateTime d = currentDate.PreviousMonthLastDay();
      
              return new DateTime( d.Year, d.Month, 1 );
          }
      
          public static DateTime PreviousMonthLastDay( this DateTime currentDate )
          {
              return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 );
          }
      }
      

      查看此链接 http://www.codeplex.com/fluentdatetime 一些启发性的 DateTime 扩展。

      【讨论】:

        【解决方案7】:

        使用流畅的日期时间https://github.com/FluentDateTime/FluentDateTime

                var lastMonth = 1.Months().Ago().Date;
                var firstDayOfMonth = lastMonth.FirstDayOfMonth();
                var lastDayOfMonth = lastMonth.LastDayOfMonth();
        

        【讨论】:

          【解决方案8】:

          电子商务中的典型用例是信用卡到期日期,MM/yy。减去一秒而不是一天。否则,该卡将在到期月份的最后一天显示为已过期。

          DateTime expiration = DateTime.Parse("07/2013");
          DateTime endOfTheMonthExpiration = new DateTime(
            expiration.Year, expiration.Month, 1).AddMonths(1).AddSeconds(-1);
          

          【讨论】:

            【解决方案9】:

            我使用这个简单的单行:

            public static DateTime GetLastDayOfPreviousMonth(this DateTime date)
            {
                return date.AddDays(-date.Day);
            }
            

            请注意,它会保留时间。

            【讨论】:

            • 正是我想要的,我可以在三元组中使用的简洁表达式。谢谢!
            【解决方案10】:

            这是对 Mike W 的回答:

            internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
            {
                DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
                DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
                if (returnLastDayOfMonth) return lastDayOfLastMonth;
                return firstDayOfThisMonth.AddMonths(-1);
            }
            

            你可以这样称呼它:

            dateTimePickerFrom.Value = GetPreviousMonth(false);
            dateTimePickerTo.Value = GetPreviousMonth(true);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-04-03
              • 2013-11-25
              • 2014-03-22
              • 1970-01-01
              • 1970-01-01
              • 2017-01-07
              • 1970-01-01
              相关资源
              最近更新 更多