如何在2019年2月24日的格式中找到Java中的未来日期(比如今天两个月)

问题描述 投票:1回答:1

以下是我要采用的方法:

Date DateObject = new Date();
SimpleDateFormat formatDate = new SimpleDateFormat("dd MMMM yyyy");
String dateString = formatDate.format(DateObject);
System.out.println(dateString);

现在,这给了我所需格式的当前日期。我希望在此日期后两个月内以相同格式找到日期值。

我也尝试使用以下方法:

LocalDate futureDate = LocalDate.now().plusMonths(2);

这给了我想要的日期,即从现在开始的两个月但是2019-04-24格式。当我尝试使用SimpleDateFormat格式化这个日期时,它给了我非法的参数异常。

java date date-formatting localdate java-date
1个回答
4
投票

尝试使用Java 8中引入的DateTimeFormatter类,避免使用SimpleDateFormat

public static void main(String[] args) {
     LocalDate futureDate = LocalDate.now().plusMonths(2);
     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy");
     String dateStr = futureDate.format(formatter);
     System.out.println(dateStr);
}

输出:

24 April 2019

Java 8中的DateTimeFormatterSimpleDateFormat的不可变和线程安全的替代品。

© www.soinside.com 2019 - 2024. All rights reserved.