Java解析日期字符串返回错误的月份

时间:2018-03-08 08:36:29

标签: java android date simpledateformat date-parsing

我尝试解析日期字符串,但错误的月份,为什么?

new SimpleDateFormat("yyyy-MM-DD", Locale.US).parse("2018-03-08")

为什么这会将月份作为Jan返回?

请查看截图:

enter image description here

5 个答案:

答案 0 :(得分:2)

为什么不使用java.time API

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

如果您想将LocalDate转换为java.util.Date,可以关注this answer

答案 1 :(得分:1)

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.

答案 2 :(得分:0)

您需要使用dd代替DD

试试这个: -

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

答案 3 :(得分:0)

如果您要显示月份名称,请查看此tutorial,您应使用3 M并且不是当天的标准D而不是yyyy-MMM-dd

我建议您尝试{{1}}

答案 4 :(得分:0)

我在下面尝试过此操作,将DD更改为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();
        }