0

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
  • 25,419
  • 17
  • 47
  • 88
Shabar
  • 2,617
  • 11
  • 57
  • 98
  • I recommend you don’t use `Calendar` and `SimpleDateFormat`. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 02 '20 at 09:52
  • On which date did you run your snippets? Asking because I cannot find a way to reproduce your results. When I run today (March 2, 2020), I get `0/1/2020` from the first snippet, `01/01/2020` from the second one. Assuming you ran on March 1, I get `11/29/2019` and `12/363/2019`. – Ole V.V. Mar 02 '20 at 09:59

2 Answers2

1

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.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
1

java.time

Do use java.time, the modern Java date and time API, for your date and time work. It is so much nicer to work with than the old, poorly designed and long outdated date-time classes including Calendar and SimpleDateFormat.

And do use a formatter whenever you need to format a date into a string.

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");

    LocalDate today = LocalDate.now(ZoneId.of("Australia/Melbourne"));
    LocalDate then = today.minusDays(1).minusMonths(2);

    String myDate= then.format(dateFormatter);

    System.out.println(myDate);

Output when I ran today, March 2, 2020:

01/01/2020

Tutorial link: Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161