4

I am trying to get a Date object in the format YYYY-MM-DD representing the current system date. Below is my attempt:

Date todayDate = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
String todayString = formatter.format(todayDate);

The values are as follows:

todayDate: Mon May 15 16:24:47 GMT+01:00 2017

todayString: 2017-24-15

Having tried this a couple of times I noticed the todayString is not made up of YYYY-MM-DD but YYYY-[minutes][minutes]-DD.

How might I get the current date in the YYYY-MM-DD format?

petehallw
  • 1,014
  • 6
  • 21
  • 49
  • I see that it's a duplicate but why the down votes? It's already been marked as a duplicate and I don't see why it's a particularly poor question. – petehallw May 16 '17 at 07:26
  • I agree the question is fine, one might have expected a little more research, like checking the documentation, but it’s got MCVE and a fine observation and description of the actual behaviour. – Ole V.V. May 16 '17 at 08:10
  • If you can, use `LocalDate`. Its `toString()` gives you the format you want, no need for a formatter. Additionally, if you do use a `DateTimeFormatter` with `mm` instead of `MM`, it will tell you something is wrong (`UnsupportedTemporalTypeException: Unsupported field: MinuteOfHour`). – Ole V.V. May 16 '17 at 08:13
  • @OleV.V. Thanks for the comments, I'll definitely look into using `LocalDate`! – petehallw May 16 '17 at 08:22
  • Tutorial: https://docs.oracle.com/javase/tutorial/datetime/iso/date.html. Which Java version are you using? Asking because `LocalDate` comes built-in with Java 8 and 9 but is available for Java 6 and 7 too. – Ole V.V. May 16 '17 at 08:26
  • Ah, you said Android. Have a look at [this question: How to use ThreeTenABP in Android Project](http://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. May 16 '17 at 08:28
  • 1
    @OleV.V. I think it's crazy that this functionality has not been present in Java before version 8... Thanks for the link, I'm reading through it! – petehallw May 16 '17 at 08:59
  • @petehallw I suspect the down-votes are for posting a Question without bothering to search first. This topic has been addressed hundreds of times already. Your Question adds no value to Stack Overflow, only distraction and waste of readers’ time, hence the down-votes. Tip for future reference: Virtually all basic date-time questions have already been asked and answered. – Basil Bourque May 16 '17 at 15:55

1 Answers1

5

Change this:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");

to this:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

mm stands for the minutes, while MM (capitalized) stands for the month

Daniele
  • 4,163
  • 7
  • 44
  • 95