月份不缩写时如何将日期字符串转换为localDate

问题描述 投票:0回答:1

我正在尝试使用 LocalDate 转换具有完整月份名称的日期字符串,但我收到 java.time.format.DateTimeParseException: Text Could not be parsed at index 6 我尝试在网上查找但找不到合适的解决方案。

public void iConvertDate() {
        String datevalue = String.valueOf(UIPgAct.dateFormat("10 March 2024", "dd MMM yyyy"));
    }
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public LocalDate dateFormat(String dateToFormat, String fromFormatPattern) {
        LocalDate dateLocal = null;
        if (dateToFormat != null) {
           try {
               DateTimeFormatter dtf = DateTimeFormatter.ofPattern(fromFormatPattern, Locale.US);
               dateLocal = LocalDate.parse(dateToFormat, dtf);
               break;
           } catch (Exception e) {
               System.out.println(e.getMessage());
           }
        }
        return dateLocal;
    }

我尝试了“dd MMM yyyy”、“dd-MMM-yyyy”格式,但它们都返回相同的错误。我被困在这里了。 谢谢

java-8 localdate
1个回答
0
投票

如果我们想解析完整的月份名称,例如 10 March 2024”,我们需要使用 “dd MMMM yyyy”日期格式化程序。

尝试以下方法

LocalDate date= dateFormat("10 March 2024", "dd MMMM yyyy")

public LocalDate dateFormat(String dateToFormat, String fromFormatPattern) {
        LocalDate dateLocal = null;
        if (dateToFormat != null) {
            try {
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern(fromFormatPattern, Locale.US);
                dateLocal = LocalDate.parse(dateToFormat, dtf);
                //break;
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        return dateLocal;
    }

这将返回格式化日期:2024-03-10

© www.soinside.com 2019 - 2024. All rights reserved.