How to parse month full form string using DateFormat in Java?

后端 未结 3 754
面向向阳花
面向向阳花 2020-12-03 00:37

I tried this:

DateFormat fmt = new SimpleDateFormat(\"MMMM dd, yyyy\");
Date d = fmt.parse(\"June 27, 2007\");

error:

Excepti

相关标签:
3条回答
  • 2020-12-03 00:55
    val currentTime = Calendar.getInstance().time
    SimpleDateFormat("MMMM", Locale.getDefault()).format(date.time)
    
    0 讨论(0)
  • 2020-12-03 01:05

    You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.

    Try specifying the locale you wish to use, for example Locale.US:

    DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
    Date d = fmt.parse("June 27,  2007");
    

    Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.

    0 讨论(0)
  • 2020-12-03 01:10

    Just to top this up to the new Java 8 API:

    DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
    TemporalAccessor ta = formatter.parse("June 27, 2007");
    Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
    Date d = Date.from(instant);
    assertThat(d.getYear(), is(107));
    assertThat(d.getMonth(), is(5));
    

    A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.

    0 讨论(0)
提交回复
热议问题