Search code examples
javaapidatesimpledateformat

Date format API is breaking today


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?


Solution

  • 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 );