用Java格式化LocalDate:"2020年3月26日"的模式是什么 [英] Formatting LocalDate in Java: What's the pattern for "March 26 2020"
问题描述
我似乎无法提出"2020年3月26日"的模式(无逗号).有人可以帮忙吗?我已经尝试过 DateTimeFormatter.ofPattern("MMMM dd yyyy")
和 DateTimeFormatter.ofPattern("MMM dd yyyy")
.任何帮助将不胜感激!
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!
最小的可复制示例:
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
线程"main"中的异常;java.time.format.DateTimeParseException:无法在索引0处解析文本"2020年3月26日"
Exception in thread "main" java.time.format.DateTimeParseException: Text 'March 26 2020' could not be parsed at index 0
预期输出为
2020-03-26
在格式模式中使用 MMM
代替,例外是相同的.
With MMM
in the format pattern instead the exception is the same.
推荐答案
使用模式 MMMM dd uuuu
和 Locale.ENGLISH
.
演示:
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);
}
}
输出:
2020-03-26
这篇关于用Java格式化LocalDate:"2020年3月26日"的模式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!