2

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.

deepee1
  • 12,290
  • 4
  • 29
  • 43
Stephanie
  • 61
  • 1
  • 4
  • What do you mean by "next quarter"? How 03/31/2015 is the last day of the next quarter of 12-02-2014? – Nikolay Kostov Jan 28 '15 at 22:45
  • Take a look at [Calculate the start-date and name of a quarter from a given date](http://stackoverflow.com/a/1492129/2091410) - the answer there shows how to calculate the beginning *and* the end of the current quarter, and you can adapt that to go out an additional quarter. – Ed Gibbs Jan 28 '15 at 22:46
  • 2
    I've changed the dates to ISO date format to accommodate both US and non-US users. – Enigmativity Jan 28 '15 at 22:56
  • sorry for the confusion. because for 12-02-2014, the next quarter is from Jan to March on 2015, and the last day of the quarter should be March 31, 2015. So no matter what day is it, only depends on the months. another example is, for 08-04-2014, since the current quarter is from July, 2014 to Sept, 2014, so the next quarter will be 0ct 2014 to Dec 2014. So the last day of next quarter will be Dec. 31, 2014. Is that make sense? – Stephanie Jan 29 '15 at 00:41

2 Answers2

9

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:

results

Is that what you wanted?

Enigmativity
  • 105,241
  • 11
  • 83
  • 163
  • 1
    Not positive, but I think the user is asking for the quarter following the quarter you are giving. For example... a December date would yield a March-31 result. – deepee1 Jan 28 '15 at 23:09
  • @deepee1 - The question is a bit confusing, but I went with the example date that the OP provided rather than the wording of the problem. If it is the actual **next** quarter then it would be a case of replacing the first `3` with `6`. – Enigmativity Jan 28 '15 at 23:13
  • 100% agreed on the ambiguity of the question. Approach is sound in either case. – deepee1 Jan 28 '15 at 23:16
  • thank you for replying! and sorry for the confusing. I think deeppee1 represented what I mean.! very appreciate for help! – Stephanie Jan 29 '15 at 00:37
  • if you put "2021-03-31" as input this algorithm return "2021-03-30" – Luke May 13 '21 at 15:03
  • @luke - Well spotted. I've updated the answer. – Enigmativity May 13 '21 at 23:09
1

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