-5

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:

enter image description here

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210
  • 4
    Use `dd` not `DD` . The former is for day in month, the latter for day in year . – Arnaud Mar 08 '18 at 08:37
  • 1
    try new SimpleDateFormat("yyyy-MM-dd", Locale.US).parse("2018-03-08"); – Vishal Sanghani Mar 08 '18 at 08:40
  • Also note that calling `setLenient(false)` on your `SimpleDateFormat` before using it, would prevent some attempts to interpret a wrong `String`. In your case attempting to parse the `String` would give a `java.text.ParseException: Unparseable date: "2018-03-08"` . – Arnaud Mar 08 '18 at 09:45
  • 1
    As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. It will also alleviate your problem: the modern `LocalDate` class parses your `2018-03-08` without any explicit formatter because it is in its default format (ISO 8601). So no way to get the format pattern string wrong. – Ole V.V. Mar 08 '18 at 12:57

5 Answers5

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 8th day on this year (2018) which means January 8th.

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

pandd
  • 103
  • 4
J J
  • 70
  • 6
2

Why not use the java.time API?

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

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

pandd
  • 103
  • 4
0

You need to use dd instead of DD

Try this :-

new SimpleDateFormat("yyyy-MM-dd", Locale.US).parse("2018-03-08");
akhilesh0707
  • 6,709
  • 5
  • 44
  • 51
Santanu Sur
  • 10,997
  • 7
  • 33
  • 52
0

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

Dan
  • 2,020
  • 5
  • 32
  • 55
0

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();
        }
oldcode
  • 1,669
  • 3
  • 22
  • 41