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

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

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 requirement in.

The survey must include all of the service requests for the previous month. So if it is April 15th, I need all of Marches request ids.

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

I just can't think of the dates easily without a switch. Unless I'm blind and overlooking an internal method of doing it.

ベストアンサー1

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.

おすすめ記事