简体   繁体   中英

Formatting LocalDate in Java: What's the pattern for “March 26 2020”

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") . Any help would be appreciated!

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.

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

Try this

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

Worked for me just fine, Output:

December 10 2020

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM