Bil*_*ard 48
你可以用
int quarter = (myDate.getMonth() / 3) + 1;
Run Code Online (Sandbox Code Playgroud)
请注意,虽然getMonth已被弃用:
从JDK 1.1版开始,由Calendar.get(Calendar.MONTH)取代.
abd*_*nce 35
在Java 8及更高版本中,java.time类具有更简单的版本.使用LocalDate和IsoFields
LocalDate.now().get(IsoFields.QUARTER_OF_YEAR)
Run Code Online (Sandbox Code Playgroud)
Out*_*mer 12
您将不得不编写自己的代码,因为每个企业的术语"季度"是不同的.你不能只做这样的事情:
Calendar c = /* get from somewhere */
int month = c.get(Calendar.MONTH);
return (month >= Calendar.JANUARY && month <= Calendar.MARCH) ? "Q1" :
(month >= Calendar.APRIL && month <= Calendar.JUNE) ? "Q2" :
(month >= Calendar.JULY && month <= Calendar.SEPTEMBER) ? "Q3" :
"Q4";
Run Code Online (Sandbox Code Playgroud)
eri*_*son 10
由于季度是本地化(西方)概念,因此请指定区域设置而不是使用平台默认值:
Calendar cal = Calendar.getInstance(Locale.US);
/* Consider whether you need to set the calendar's timezone. */
cal.setTime(date);
int month = cal.get(Calendar.MONTH); /* 0 through 11 */
int quarter = (month / 3) + 1;
Run Code Online (Sandbox Code Playgroud)
这将避免在非西方日历上获得第13个月(Calendar.UNDECIMBER),以及由于较短的月份而导致的任何偏差.
如果你有
private static final int[] quarters = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};
Run Code Online (Sandbox Code Playgroud)
那么电流quarter是
private static final int thisQuarter = quarters[thisMonth];
Run Code Online (Sandbox Code Playgroud)
哪里thisMonth是
private static final int thisMonth = cal.get(Calendar.MONTH);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69815 次 |
| 最近记录: |