Java:如何根据给定日期获取季度

时间:2020-08-13 22:26:43

标签: java

我正在使用Java8。我需要编写Java代码以根据给定日期显示季度。但是第一季度是从4月1日到6月30日。

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

2 个答案:

答案 0 :(得分:2)

创建一个YearMonth的实例,并减去3个月:

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

那么四分之一数是通过算术运算获得的:

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

然后只需访问以下字段:

String s = "Q" + q + ym.getYear();

答案 1 :(得分:0)

此功能可以解决您的问题

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;
}