如何根据给定日期获取季度年份。

huangapple go评论75阅读模式
英文:

Java : How to get quarter year based on given date

问题

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

给定日期:- 在2020/01/01和2020/03/31之间 --> Q42019
在2020/04/01和2020/06/30之间 --> Q12020
在2020/07/01和2020/09/30之间 --> Q22020
在2020/10/01和2020/12/31之间 --> Q32020
在2021/01/01和2021/03/31之间 --> Q42020

英文:

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

答案1

得分: 3

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

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

然后通过算术计算获取季度号:

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

然后只需访问字段:

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

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();

答案2

得分: 2

这个函数可以解决你的问题

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;
}
英文:

This function can solve your problem

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

    if(month &gt;=1 &amp;&amp; month &lt;= 3) {
        quarterCode = &quot;Q4&quot;;
        year = year - 1;
    }
    else if(month &gt;=4 &amp;&amp; month &lt;= 6) {
        quarterCode = &quot;Q1&quot;;
    }
    else if(month &gt;=7 &amp;&amp; month &lt;= 9) {
        quarterCode = &quot;Q2&quot;;
    }
    else if(month &gt;=10 &amp;&amp; month &lt;= 12) {
        quarterCode = &quot;Q3&quot;;
    }
    return quarterCode + year;
}

huangapple
  • 本文由 发表于 2020年8月14日 06:26:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63404039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定