提问者:小点点

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


以下是我要采用的方法:

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格式化此日期时,它给了我非法参数异常。


共1个答案

匿名用户

尝试使用Java8中介绍的DateTimeFortex类,避免使用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

Java8中的DateTimeFortex是SimpleDateFormat的不可变且线程安全的替代方案。