如何以 2019 年 2 月 24 日的格式查找 Java(比如从今天起两个月)的未来日期
How to find a Future Date in Java(say two months from today) in 24 February 2019 format
以下是我要采用的方法:
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 格式化此日期时,它给了我非法参数异常。
尝试使用DateTimeFormatter
class Java 8,避免使用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
.
的不可变且线程安全的替代方案
以下是我要采用的方法:
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 格式化此日期时,它给了我非法参数异常。
尝试使用DateTimeFormatter
class Java 8,避免使用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
.