1

I am using java 8. I need to write a java code to display the Quarter based on given date. But the Q1 is from April 1st to June 30th.

Given Date :- between 2020/01/01 and 2020/03/31 --> Q42019
              between 2020/04/01 and 2020/06/30  --> Q12020
              between 2020/07/01 and 2020/09/30  --> Q22020
              between 2020/10/01 and 2020/12/31   --> Q32020
              between 2021/01/01 and 2021/03/31  --> Q42020
Sri Venkat
  • 43
  • 3
  • 1
    Have you tried something? If so, post it here. – akuzminykh Aug 13 '20 at 22:28
  • You would probably want to count the number of days between the dates, divide it by four, than add that to the first date. This might be useful: https://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances – Hannah B Aug 13 '20 at 22:42
  • Di you want the numbers (4 and 2019 for Q42019) or do you want the string `Q42019`? Both are easy enough when you know how. – Ole V.V. Aug 14 '20 at 09:20
  • I wrote a new and modern answer to the linked original question for you [here](https://stackoverflow.com/a/63416901/5772882). – Ole V.V. Aug 14 '20 at 17:00

2 Answers2

3

Create an instance of YearMonth, and subtract 3 months:

YearMonth ym = YearMonth.of(year, month).subtractMonths(3);

Then the quarter number is obtained by arithmetic:

int q = (ym.getMonthValue() - 1) / 3 + 1;

Then just access the fields:

String s = "Q" + q + ym.getYear();
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • 2
    I’d prefer something like `ym.format(DateTimeFormatter.ofPattern("QQQuuuu", Locale.ENGLISH))` and save the arithmetic. – Ole V.V. Aug 14 '20 at 12:17
2

This function can solve your problem

public String getQuarter(int month, int year) {
    String quarterCode = "";

    if(month >=1 && month <= 3) {
        quarterCode = "Q4";
        year = year - 1;
    }
    else if(month >=4 && month <= 6) {
        quarterCode = "Q1";
    }
    else if(month >=7 && month <= 9) {
        quarterCode = "Q2";
    }
    else if(month >=10 && month <= 12) {
        quarterCode = "Q3";
    }
    return quarterCode + year;
}
AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30
  • 1
    really nice answer, but using switch expressions might be good chice as well. they have really cool syntax. (edit: but they are not available in java8, sorry) – roozbeh sharifnasab Aug 13 '20 at 22:56