Incorrect previous day in Java Calender

SMPH :

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

Andronicus :

Your date formatting is not what you intended to do. Try the following to get the previous date (yesterday):

Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -1);
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String MyDate= df.format(now.getTime());

System.out.println(MyDate);

According to the documentation "YYYY" is a week year and "DD" is a da in year.

P.S.: By convention variable names in java are written lowercase.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18659&siteId=1