Alex Rivera | Logout

How do I discover the quarter of a given date

Asked 2012-01-02T07:10:45.080
57

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.

c#
Edit
Report

1 Answer

34

You can simply write an extension method to DateTime

public static int GetQuarter(this DateTime date)
{
    if (date.Month >= 4 && date.Month <= 6)
        return 1;
    else if (date.Month >= 7 && date.Month <= 9)
        return 2;
    else if (date.Month >= 10 && date.Month <= 12)
        return 3;
    else 
        return 4;
}

and use it as

DateTime dt = DateTime.Now;
dt.GetQuarter();
answered 2012-01-02T07:15:24.347

Your Answer