-2
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD");
System.out.println("=============new Date() ="+new Date());
    
String dateStr =format.format(new Date() );    
System.out.println("==============dateStr "+dateStr );

And see the below output

=============new Date() =Mon Feb 01 11:22:02 EST 2021
==============dateStr  = 2021-02-32

What is wrong in this code which was working fine today it broke?

Hulk
  • 6,399
  • 1
  • 30
  • 52
user5318074
  • 15
  • 1
  • 4
  • What does `breaking` mean? What is the error, symptom? What is the input that lead to that? Did you try debugging? – Omar Abdel Bari Feb 01 '21 at 16:35
  • 2
    Also note that `SimpleDateFormat` is obsolete - for new code, please use [`DateTimeFormatter`](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/time/format/DateTimeFormatter.html) – Hulk Feb 01 '21 at 16:50
  • 1
    Related: https://twitter.com/haveigotnews/status/1356207327909720065 – Andy Turner Feb 01 '21 at 17:04

1 Answers1

6

You have wrong date string format, replace "YYYY-MM-DD" with "yyyy-MM-dd". Note that the difference is that capital D refers to Day in year where as lower case d refers to day in month. See the docs

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println("=============new Date() ="+new Date());
    String dateStr =format.format(new Date() );
    System.out.println("==============dateStr "+dateStr );
arch2be
  • 306
  • 2
  • 8
  • 1
    Also, you'd probably want `yyyy`, unless you really want the week year. – Andy Turner Feb 01 '21 at 16:42
  • I got confused by that too @AndyTurner I submitted an edit for that already which needs to be approved – Omar Abdel Bari Feb 01 '21 at 16:42
  • @OmarAbdelBari I don't think you should really add such extra explanation in an edit: by all means make the suggestion to describe why it works, but give arch2be a chance to write in his/her own words. – Andy Turner Feb 01 '21 at 16:44
  • Personally would not mind if someone did that to my answer. However if it's against the rules I'm not aware of that, I'd like to know. – Omar Abdel Bari Feb 01 '21 at 16:47
  • @OmarAbdelBari it's not "against the rules"; just consider that answers are part of the reputation and contribution of the answerer - with their name on it - and so they might want to phrase it/format it in a certain way; edits aren't necessarily approved by the answerer. It obviously depends on the person, so don't take it in any other way than advice :) – Andy Turner Feb 01 '21 at 16:58