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

Getting exception

Text '03/2018' could not be parsed: Unable to obtain LocalDate from TemporalAccessor:

How to parse this string and convert to Date using Java 8 having default first day of the month. Something what we do using.

TemporalAdjusters.firstDayOfMonth()
SparkOn
  • 8,806
  • 4
  • 29
  • 34

2 Answers2

6

You have two choices for converting a MM/yyyy string into a LocalDate:

  • Parse as YearMonth then convert to 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
    
  • Use a DateTimeFormatter with a default day-of-month defined:

    String date = "04/2018";
    DateTimeFormatter dateFormat = new DateTimeFormatterBuilder()
            .appendPattern("MM/yyyy")
            .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
            .toFormatter();
    LocalDate parsedDate = LocalDate.parse(date, dateFormat);
    System.out.println(parsedDate); // prints: 2018-04-01
    
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • DateTimeFormatterBuilder#toFormatter(Locale.ENGLISH) is a good practice. – SparkOn Apr 30 '18 at 19:02
  • 1
    @SparkOn If you suggest to use something like `.toFormatter(Locale.US)`, then you should also suggest to use `.ofPattern("MM/yyyy", Locale.US)`, but it doesn't affect the result, regardless of your default locale. Now, if pattern displayed month *name*, the locale would matter, but since only numbers are displayed/parsed, locale doesn't matter. – Andreas Apr 30 '18 at 19:14
0

Here's what works for me:

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
JellyRaptor
  • 725
  • 1
  • 8
  • 20
  • Lemme guess, using Joda-Time? Asking because I think the question used `java.time`, which may be considered the successor of Joda-Time. – Ole V.V. Apr 30 '18 at 19:08