0

I am new to Java and I am trying to get the yesterday date with the following code:

    GregorianCalendar gc = new GregorianCalendar(2018,9,22);//<-Today
    gc.add(gc.DATE, -1);//<-Yesterday
    SimpleDateFormat dateFormatter = new SimpleDateFormat("DD-MMM-YYYY");
    System.out.println(dateFormatter.format(gc.getTime()));

The output I'm getting is:

325-XI-2018

What am I doing wrong?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
3AKOBAH
  • 105
  • 6
  • 2
    Change from "DD-MMM-YYYY" to "dd-MMM-yyyy" – forpas Oct 22 '18 at 09:42
  • Search before posting. This has been covered many many many times already on Stack Overflow. And you are using terrible legacy classes. – Basil Bourque Oct 22 '18 at 23:48
  • 1
    FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 20 '19 at 20:59

2 Answers2

2

DD-MMM-YYYY means :

  • DD : Day in year
  • MMM : Month in year (Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.)
  • YYYY : Week year

If you want to display the date as 22-09-2018, use the format dd-MM-yyyy.

see https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Fabien MIFSUD
  • 335
  • 5
  • 14
  • Oh, I see now! DD was the one that got me lost with that 314. – 3AKOBAH Oct 22 '18 at 10:40
  • Hey @3AKOBAH please consider upvoting and accepting the answer when it solved your issue. – Daniel W. Oct 22 '18 at 10:52
  • 1
    The terrible `SimpleDateFormat` class was supplanted years ago by [`DateTimeFormatter`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html). – Basil Bourque Apr 20 '19 at 21:00
0

The DateTimeFormatter class has lots a different ways of displaying the date and time. Check out the Oracle docs at: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html for more information and syntax

PumpkinBreath
  • 831
  • 1
  • 9
  • 22