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:
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:
This is due to the format you used as "yyyy-MM-DD"
. The parser will parse in the sequence way:
"2018-03-08"
yyyy
- will bring to the year 2018MM
- will bring to the month MARCHBut 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.
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.
You need to use dd
instead of DD
Try this :-
new SimpleDateFormat("yyyy-MM-dd", Locale.US).parse("2018-03-08");
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();
}