如何用java获取当前日期的下两个月末
时间: 2023-07-18 07:03:46 浏览: 98
可以使用Java的日期时间类来实现。具体步骤如下:
1. 获取当前日期
```java
LocalDate currentDate = LocalDate.now();
```
2. 获取下两个月的月份
```java
int nextTwoMonth = currentDate.getMonthValue() + 2;
```
需要注意的是,如果当前月份是11月或12月,那么下两个月就会跨年,此时需要对年份进行调整。
```java
int year = currentDate.getYear();
if (nextTwoMonth > 12) {
nextTwoMonth -= 12;
year++;
}
```
3. 获取下两个月末的日期
```java
LocalDate nextTwoMonthEnd = LocalDate.of(year, nextTwoMonth, 1)
.with(TemporalAdjusters.lastDayOfMonth());
```
最后,将日期格式化为指定的字符串即可。
```java
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String nextTwoMonthEndStr = nextTwoMonthEnd.format(formatter);
```
完整代码如下:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class Main {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
int nextTwoMonth = currentDate.getMonthValue() + 2;
int year = currentDate.getYear();
if (nextTwoMonth > 12) {
nextTwoMonth -= 12;
year++;
}
LocalDate nextTwoMonthEnd = LocalDate.of(year, nextTwoMonth, 1)
.with(TemporalAdjusters.lastDayOfMonth());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String nextTwoMonthEndStr = nextTwoMonthEnd.format(formatter);
System.out.println(nextTwoMonthEndStr);
}
}
```
输出结果为当前日期的下两个月末,例如今天是2022年8月1日,则输出结果为2022-10-31。
阅读全文