-2

I can't seem to come up with a pattern for "March 26 2020" (no comma). Can someone help? I've tried DateTimeFormatter.ofPattern("MMMM dd yyyy") and DateTimeFormatter.ofPattern("MMM dd yyyy").

Minimal reproducible example:

    String strDate = "March 26 2020";
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM dd uuuu");
    LocalDate date = LocalDate.parse(strDate, dtf);
    System.out.println(date);

On my computer this throws

Exception in thread "main" java.time.format.DateTimeParseException: Text 'March 26 2020' could not be parsed at index 0

Expected output was

2020-03-26

With MMM in the format pattern instead the exception is the same.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
CNDyson
  • 1,687
  • 7
  • 28
  • 63

2 Answers2

5

Use the pattern, MMMM dd uuuu with Locale.ENGLISH.

Demo:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

class Main {
    public static void main(String[] args) {
        String strDate = "March 26 2020";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM dd uuuu", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(strDate, dtf);
        System.out.println(date);
    }
}

Output:

2020-03-26
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

Try this

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM' 'dd' 'yyyy", Locale.ENGLISH)

Worked for me just fine, Output:

December 10 2020
Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • 1
    You do not need to specify the space between `MMMM` and `dd` or between `dd` and `yyyy` explicitly using `' '`. You can simply put the space without using single quotes. – Arvind Kumar Avinash Dec 10 '20 at 16:44
  • I've seen sometimes it could make a difference – Michael Gantman Dec 10 '20 at 17:20
  • 1
    @MichaelGantman No, for a space never. Some do recommend the single quotes anyway, it’s probably a matter of taste. – Ole V.V. Dec 10 '20 at 18:49
  • 1
    It’s even in [the official documentation](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html), @ArvindKumarAvinash: *… it is recommended to use single quotes around all characters that you want to output directly to ensure that future changes do not break your application.* – Ole V.V. Nov 05 '22 at 08:13
  • Thanks, @OleV.V. for the valuable information. I'm not sure whether they have assumed that space characters will always be parsed without quotes or whether the documentation needs to be updated. They say *Any non-letter character, other than '[', ']', '{', '}', '#' and the single quote will be output directly.* – Arvind Kumar Avinash Nov 05 '22 at 09:42
  • 1
    @ArvindKumarAvinash I am not sure either. And I most often do not follow this particular recommendation. – Ole V.V. Nov 05 '22 at 09:44