以下是我要采用的方法:
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 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中的DateTimeFormatter
是SimpleDateFormat
的不可变和线程安全的替代品。