Skip to content Skip to sidebar Skip to footer

Java Parse Date String Returns Wrong Month

I try to parse a date string, but get wrong month, why? new SimpleDateFormat('yyyy-MM-DD', Locale.US).parse('2018-03-08') Why this returns month as Jan? Please check screenshot:

Solution 1:

Why not use the java.time API?

LocalDatelocalDate= LocalDate.parse("2018-03-08");

If you want to convert the LocalDate to a java.util.Date, you can follow this answer.

Solution 2:

This is due to the format you used as "yyyy-MM-DD". The parser will parse in the sequence way:

  • Your input value is "2018-03-08"
  • yyyy - will bring to the year 2018
  • MM - will bring to the month MARCH

But what is DD? It's the number of the days from the beginning of the year. So here it moved back to 8 day on this year (2018) which means January 8.

That's why you are seeing January instead of March.

Solution 3:

Looking at this tutorial if you are trying to display the month name you should use 3 M’s and isn’t the standard for the day to be d and not D

I would suggest trying yyyy-MMM-dd

Solution 4:

I tried this below and it is working fine by changing the DD to dd

try {
            Date date=  new SimpleDateFormat("yyyy-MM-dd",Locale.US).parse("2018-03-08");

            Calendar calendar= Calendar.getInstance();
            calendar.setTime(date);
            Log.d("MONTH ","" + calendar.get(Calendar.MONTH));



        } catch (ParseException e) {
            e.printStackTrace();
        }

Solution 5:

You need to use dd instead of DD

Try this :-

newSimpleDateFormat("yyyy-MM-dd", Locale.US).parse("2018-03-08");

Post a Comment for "Java Parse Date String Returns Wrong Month"