java Calendar类获取当前年的最后一天
时间: 2023-06-05 13:07:02 浏览: 172
The last day of the current year can be obtained using the Calendar class in Java. Here is an example code snippet:
```
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, 11); // 11 represents December
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Last day of " + year + " is " + lastDay);
```
This code sets the year to the current year, sets the month to December, and then retrieves the last day of the month using the `getActualMaximum()` method of the Calendar class.
相关问题
java Calendar类获取当前年的最后一
天是什么日期?
回答:当前年的最后一天可以使用 Calendar.getActualMaximum(Calendar.DAY_OF_YEAR) 方法来获取,然后再通过 Calendar.set(Calendar.DAY_OF_YEAR, 天数) 方法设置当前日期到获取的那一天即可。
calendar 获取季度的第一天_java获取当前年、半年、季度、月、日、小时 开始结束时间等...
获取当前季度的第一天可以使用下面的代码:
```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` 对象即可。
阅读全文