DateFormat gives the wrong answer

I used the code below to format the date. But this gives an unexpected result when I give the data in the wrong format.

DateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");`

String dateVal = "3/8/2016 12:00:00 AM";

try {
    Date date = inputFormat.parse(dateVal);
    String formattedVal = outputFormat.format(date);
    System.out.println("formattedVal : "+formattedVal);
} catch (ParseException pe) {
    throw pe;
}

In the above case, the output is formattedVal: 0009-02-05.

Instead of throwing a Parse exception, it parses the value and gives me the wrong conclusion. Can someone please help me understand this abnormal behavior.

+4
source share
4 answers

SimpleDateFormat Calendar . Calendar : . , , .

SimpleDateFormat :

inputFormat.setLenient(false);

java.time JodaTime, Java 8 .

+3

, .

3/8/2016 year/month/day, :

  • = 3
  • month = 8 → 8 - 0.667 .
  • = 2016 → 2016 ~ 5.5

= 3 + 5.5 = 8.5 + 0.667 = 9.17. 05 09.

+7

SimpleDateFormat:

Year: ... Any other numeric string, such as a single-digit string, three or more bit strings, or a two-digit string that is not all digits (for example, “-1”), is interpreted literally. So, “01/02/3” or “01/02/003” are analyzed in the same way as on January 2, 3 years. Similarly, "01/02 / -3" is analyzed as January 2, 4 BC.

+1
source
public static void main(String[] args) {
        try {

            String dateVal = "3/8/2016 12:00:00 AM";
            DateFormat inputFormat = new SimpleDateFormat("d/M/yyyy hh:mm:ss a");//the pattern here need to bee equals the 'dateVal' format

            DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");

            Date date = inputFormat.parse(dateVal);
            String formattedVal = outputFormat.format(date);
            System.out.println("formattedVal : "+formattedVal);
        } catch (ParseException pe) {
            System.err.println("cannot parse date...");
        }
    }
0
source

All Articles