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
.