英文:
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 = "";
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论