java 获取指定季度的开始时间和结束时间
时间: 2023-09-03 21:15:52 浏览: 240
可以使用 Calendar 类来获取指定季度的开始时间和结束时间。下面是一个示例代码:
```java
import java.util.Calendar;
public class QuarterTime {
public static void main(String[] args) {
int year = 2021; // 年份
int quarter = 1; // 季度,1表示第一季度,2表示第二季度,以此类推
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
// 获取季度的月份范围
int startMonth = (quarter - 1) * 3 + 1;
int endMonth = startMonth + 2;
// 设置季度的开始时间
calendar.set(Calendar.MONTH, startMonth - 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long startTimeInMillis = calendar.getTimeInMillis();
// 设置季度的结束时间
calendar.set(Calendar.MONTH, endMonth - 1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
long endTimeInMillis = calendar.getTimeInMillis();
System.out.println("开始时间:" + startTimeInMillis);
System.out.println("结束时间:" + endTimeInMillis);
}
}
```
在上面的代码中,我们首先设置了年份和季度,然后根据季度的月份范围计算出开始时间和结束时间。在设置时间时,我们使用了 Calendar 类的 set 方法来设置年、月、日、时、分、秒和毫秒。注意,在设置月份时需要减一,因为 Calendar 类中的月份是从0开始的。
最后,我们使用 getTimeInMillis 方法来获取时间的毫秒表示。如果需要获取 Date 对象,可以使用 new Date(startTimeInMillis) 和 new Date(endTimeInMillis) 来构造。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)