In c#, how to get the last day of next quarter giving the date?
For example, given date is 2014-12-02, I need to return the date 2015-03-31.
In c#, how to get the last day of next quarter giving the date?
For example, given date is 2014-12-02, I need to return the date 2015-03-31.
Very simple:
var given = new DateTime(2014, 02, 12);
var result =
given.Date
.AddDays(1 - given.Day)
.AddMonths(3 - (given.Month - 1) % 3)
.AddDays(-1);
//2014-03-31
If I input 2014-08-12
I get 2014-09-30
.
Here are the results for the start of each month for the year:
Is that what you wanted?
Be carefull with this code! For example date 31.01.2018 will return 30.03.2018. This will work as expected:
var given = new DateTime(2018, 01, 31);
var result =
given.Date
.AddMonths(3 - (given.Month - 1) % 3);
result = result.AddDays(-result.Day);
//2018-03-31
I generally recommend working with the the first day of a month as much as possible. This tends to keep things simpler.
For example, when querying data based on such dates, < FirstDayOfNextQuarter
is always correct. Using <=
is much harder: what is the greatest possible time component? yyyy-MM-dd 23:59:59
? yyyy-MM-dd 23:59:59.999999
? This raises questions when we read it and thus warrants avoiding.
Here is a simple way to obtain the start date of the quarter for any given DateTime
.
If you are certain that you want to work with end dates, then converting "the start date of the current quarter" to "the end of date of the next quarter" is simple: go forward two quarters (6 months), then go back 1 day.
var endDateOfNextQuarter = GetFirstDayOfCurrentQuarter(dateTime).AddMonths(6).AddDays(-1);
Again, by performing calculations with Day=1
, it is very easy to verify correctness. Our intermediate values do not tangle with whether the last day is 28, 39, 30, or 31, because we only work with the first day of any month. Only at the very end do we obtain the last day of the month that we are looking for.