字符串到日期Java 8的月份年份

时间:2018-04-30 18:42:05

标签: java java-8

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/yyyy");
LocalDate parsedDate = LocalDate.parse(entryOne.getKey(), dateFormat)

获得例外

  

无法解析文本'03 / 2018':无法从TemporalAccessor获取LocalDate:

如何解析此字符串并使用具有默认的第一天的Java 8转换为Date。我们使用的东西。

TemporalAdjusters.firstDayOfMonth()

2 个答案:

答案 0 :(得分:6)

onCreate()/onPause()字符串转换为MM/yyyy

有两种选择
  • 解析为LocalDate,然后转换为YearMonth

    LocalDate
  • 使用String date = "04/2018"; DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/yyyy"); YearMonth yearMonth = YearMonth.parse(date, dateFormat); LocalDate parsedDate = yearMonth.atDay(1); System.out.println(parsedDate); // prints: 2018-04-01 并定义默认的日期:

    DateTimeFormatter

答案 1 :(得分:0)

这对我有用:

String dateAsString = "03/2018";
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/yyyy");
DateTime dt = fmt.parseDateTime(dateAsString);
LocalDateTime ldt = new LocalDateTime(dt);
int dayOfWeek = ldt.getDayOfWeek(); //has value of 4 since Thursday was the first day of March