I wanted to get the previous day using Calender
in Java. I am using the below code.
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -1);
now.add(Calendar.MONTH, -2);
myDate = now.get(Calendar.MONTH) + "/" + now.get(Calendar.DATE) + "/" + now.get(Calendar.YEAR);
System.out.println(myDate);
Output: 2/31/2020
The problem is above doesn't work all the time. As above if the current date is 03/01/2020
you get the above results. But February cannot have 31
. Is there an option within Calendar
lib to handle this?
And if I use below with formatting it gives completely different values.
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -1);
now.add(Calendar.MONTH, -2);
SimpleDateFormat df = new SimpleDateFormat("MM/DD/YYYY");
String myDate= df.format(now.getTime());
System.out.println(myDate);
Output: 03/91/2020