java 获取当月第一天和最后一天
时间: 2024-01-30 10:02:05 浏览: 193
java 获取时间 本周本年本月第一天最后一天
5星 · 资源好评率100%
获取当月第一天的Java代码:
```java
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1); // 设置为当月第一天
Date firstDayOfMonth = calendar.getTime();
```
获取当月最后一天的Java代码:
```java
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); // 设置为当月最后一天
Date lastDayOfMonth = calendar.getTime();
```
或者使用Java 8的新日期时间API:
```java
LocalDate now = LocalDate.now();
LocalDate firstDayOfMonth = now.withDayOfMonth(1);
LocalDate lastDayOfMonth = now.withDayOfMonth(now.lengthOfMonth());
```
阅读全文