我如何发现给定日期的季度?
给定一个 java.util.Date 对象,我该如何找到它所在的 Quarter?
Given a java.util.Date object how do I go about finding what Quarter it's in?
假设 Q1 = 1 月 2 月 3 月,Q2 = 4 月、5 月、6 月等
Assuming Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc.
推荐答案
从 Java 8 开始,季度可作为字段访问,使用 java.time 包.
Since Java 8, the quarter is accessible as a field using classes in the java.time package.
import java.time.LocalDate;
import java.time.temporal.IsoFields;
LocalDate myLocal = LocalDate.now();
quarter = myLocal.get(IsoFields.QUARTER_OF_YEAR);
在旧版本的 Java 中,您可以使用:
In older versions of Java, you could use:
import java.util.Date;
Date myDate = new Date();
int quarter = (myDate.getMonth() / 3) + 1;
请注意,尽管 getMonth 很早就被弃用了:
Be warned, though that getMonth was deprecated early on:
从 JDK 1.1 版开始,由 Calendar.get(Calendar.MONTH) 取代.
As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH).
相反,您可以像这样使用 Calendar
对象:
Instead you could use a Calendar
object like this:
import java.util.Calendar;
import java.util.GregorianCalendar;
Calendar myCal = new GregorianCalendar();
int quarter = (myCal.get(Calendar.MONTH) / 3) + 1;
相关文章