Get the previous month's first and last day dates in c#

后端 未结 10 1453
眼角桃花
眼角桃花 2020-12-02 06:28

I can\'t think of an easy one or two liner that would get the previous months first day and last day.

I am LINQ-ifying a survey web app, and they squeezed a new requ

相关标签:
10条回答
  • 2020-12-02 07:01

    using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime

            var lastMonth = 1.Months().Ago().Date;
            var firstDayOfMonth = lastMonth.FirstDayOfMonth();
            var lastDayOfMonth = lastMonth.LastDayOfMonth();
    
    0 讨论(0)
  • 2020-12-02 07:03

    I use this simple one-liner:

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

    Be aware, that it retains the time.

    0 讨论(0)
  • 2020-12-02 07:06
    var today = DateTime.Today;
    var month = new DateTime(today.Year, today.Month, 1);       
    var first = month.AddMonths(-1);
    var last = month.AddDays(-1);
    

    In-line them if you really need one or two lines.

    0 讨论(0)
  • 2020-12-02 07:10

    If there's any chance that your datetimes aren't strict calendar dates, you should consider using enddate exclusion comparisons... This will prevent you from missing any requests created during the date of Jan 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);
    
    0 讨论(0)
提交回复
热议问题