Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The following are the Quarters for a financial year

April to June          - Q1
July to Sep            - Q2
Oct to Dec             - Q3
Jan to March           - Q4

If the month of an input date lies as above I need the output for in terms of Quarter number.

For Example,

If I give an input date (say january 2nd) , I need the output as Q4.

If I give input as (Jun 5), output should give Q1.

Based on input date I need the Quarter number.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
190 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you prefer short and concise solutions without branching and arrays, here is my preferred solution.

Normal Quarter:

public static int GetQuarter(this DateTime date)
{
    return (date.Month + 2)/3;
}

Financial Year Quarter:

public static int GetFinancialQuarter(this DateTime date)
{
    return (date.AddMonths(-3).Month + 2)/3;
}

Integer division will truncate decimals, giving you an integer result. Place methods into a static class and you will have an extension method to be used as follows:

date.GetQuarter()
date.GetFinancialQuarter()

See dotnetfiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...