Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I discover the quarter of a given date

Tags:

c#

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.

like image 861
venkat Avatar asked Jan 02 '12 07:01

venkat


2 Answers

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

like image 76
wezzix Avatar answered Sep 18 '22 16:09

wezzix


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(); 
like image 32
Haris Hasan Avatar answered Sep 19 '22 16:09

Haris Hasan