calendar 获取季度的第一天_java获取当前年、半年、季度、月、日、小时 开始结束时间等...
时间: 2023-10-13 10:05:06 浏览: 159
获取当前季度的第一天可以使用下面的代码:
```java
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int quarter = (month - 1) / 3 + 1;
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, (quarter - 1) * 3);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayOfQuarter = calendar.getTime();
```
这段代码先获取当前的年份和月份,然后通过月份计算出当前处于哪个季度,然后将月份设置为季度的第一个月,天数设置为1,从而得到当前季度的第一天。
获取当前年、半年、季度、月、日、小时的开始和结束时间可以使用下面的代码:
```java
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int quarter = (month - 1) / 3 + 1;
int halfYear = month <= 6 ? 1 : 2;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayOfYear = calendar.getTime();
calendar.set(Calendar.MONTH, halfYear == 1 ? 5 : 11);
calendar.set(Calendar.DAY_OF_MONTH, halfYear == 1 ? 30 : 31);
Date lastDayOfHalfYear = calendar.getTime();
calendar.set(Calendar.MONTH, (quarter - 1) * 3);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayOfQuarter = calendar.getTime();
calendar.set(Calendar.MONTH, (quarter - 1) * 3 + 2);
calendar.set(Calendar.DAY_OF_MONTH, 31);
Date lastDayOfQuarter = calendar.getTime();
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date startOfDay = calendar.getTime();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date endOfDay = calendar.getTime();
```
这段代码首先获取当前的年份、月份、季度、半年份、日、小时、分钟和秒数。然后分别计算出当前年的第一天、上半年的最后一天、当前季度的第一天、当前季度的最后一天、当前日的开始时间和结束时间。最后将这些时间转换为 `Date` 对象即可。
阅读全文