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.
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
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(); If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With