简体   繁体   中英

How to find a Future Date in Java(say two months from today) in 24 February 2019 format

Below is the approach I am going with :

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

Now this gives me the current date in desired format. I want to find the Value of Date in same format exactly two months from this date.

I also tried to work with below approach :

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

This gives me the date I want which is two months from now but in 2019-04-24 format. When I tried to format this date using SimpleDateFormat it is giving me Illegal Argument Exception.

Try using the DateTimeFormatter class introduced in Java 8, avoid using the 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);
}

Output:

24 April 2019

The DateTimeFormatter in Java 8 is immutable and thread-safe alternative to SimpleDateFormat .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM