Java 使用LocalDate将一个日期更改为另一个日期格式

Java 使用LocalDate将一个日期更改为另一个日期格式,java,spring-boot,date,timezone,Java,Spring Boot,Date,Timezone,我有以下的输入作为参考 Map<String,String> 1) MM dd yyyy = 08 10 2019 2) dd MM yyyy = 10 05 2019 3) dd MM yyyy = 05 10 2008 4) yyyy dd MM = 2001 24 01 但是“SimpleDataFormat.parse()”将转换并使用时区为我提供日期。转换时我不需要时区。我想直接把一种日期格式转换成另一种。我正在探索LocalDate作为Java8特性。但如果我尝试,

我有以下的输入作为参考

Map<String,String>

1) MM dd yyyy = 08 10 2019
2) dd MM yyyy = 10 05 2019
3) dd MM yyyy = 05 10 2008
4) yyyy dd MM =  2001 24 01
但是“SimpleDataFormat.parse()”将转换并使用时区为我提供日期。转换时我不需要时区。我想直接把一种日期格式转换成另一种。我正在探索LocalDate作为Java8特性。但如果我尝试,它是失败的

DateTimeFormatter target = DateTimeFormatter.ofPattern(eachFormat);
LocalDate localDate = LocalDate.parse(parsedDate.get(eachFormat),target);
请帮助我使用LocalDate和DateTimeFormatter

编辑1:好的,我不适合键入地图示例,这是我的实际地图 进入程序

1) MM dd yy = 8 12 2019
2) dd MM yy = 4 5 2007
3) yy dd MM = 2001 10 8
我猜识别并提供此地图的人使用的是SimpleDate格式化程序,因为我假设SimpleDateFormat可以将日期“8 12 2019”识别为“MM dd yy”或“MM dd YYY”或“MM d yy”或“MM d YYYYY”

但是“LocalDate”非常严格,它不是解析日期

"8 12 2019" for "dd MM yy"
它严格解析日期格式的当且仅当

"8 12 2019" is "d MM yyyy"

…现在我该怎么办?

这是正确的,旧的、麻烦的
SimpleDataFormat
解析时通常不会太注意格式模式字符串中模式字母的数量
DateTimeFormatter
,这通常是一个优势,因为它允许更好地验证字符串<代码>毫米需要两位数字表示月份<代码>yy需要两位数的年份(如2019年为19)。由于您需要能够解析一位数的月份和月份的日期以及四位数的年份,因此我建议修改格式模式字符串,以便准确地告诉
DateTimeFormatter
。我正在将
MM
更改为
M
dd
更改为
d
yy
更改为
y
。这将使
DateTimeFormatter
不必担心位数(一个字母基本上表示至少一个数字)


“但它失败了”-你能详细说明一下吗?“抛出异常”。。。。java.time.format.DateTimeParseException:无法在索引0处分析文本“9 9 2019”谢谢…当前正在工作,如果失败,将通知您…我还添加了。替换(“M{2}”,“M”);因为我还得到dd-MMM-yyyy
MMM
是月的缩写(比如
Sep
,取决于地区)
.replace(“M{2}”,“M”)
不会替换任何内容,因为
replace
deosn不理解regex
.replaceFirst(“M{2}”,“M”)
MMM
更改为
MM
,这可能不是您想要的。请尝试
.replaceFirst(“\\bMM\\b”,“M”)
。它将保持
MMM
原样,但将
MM
更改为
M
.omg…再次感谢您…在构建即将开始前的最后一分钟发现了该错误。打开stackoverflow,找到您的答案。我很高兴通知你……呸
"8 12 2019" is "d MM yyyy"
    Map<String, String> formattedDates = Map.of(
            "MM dd yy", "8 12 2019",
            "dd MM yy", "4 5 2007",
            "yy dd MM", "2001 10 8");

    for (Map.Entry<String, String> e : formattedDates.entrySet()) {
        String formatPattern = e.getKey();
        // Allow any number of digits for each of year, month and day of month
        formatPattern = formatPattern.replaceFirst("y+", "y")
                .replace("dd", "d")
                .replace("MM", "M");
        DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern(formatPattern);
        LocalDate date = LocalDate.parse(e.getValue(), sourceFormatter);
        System.out.format("%-11s was parsed into %s%n", e.getValue(), date);
    }
8 12 2019   was parsed into 2019-08-12
4 5 2007    was parsed into 2007-05-04
2001 10 8   was parsed into 2001-08-10