Java:无法从 TemporalAccessor 获取 LocalDate

2024-02-27

我正在尝试更改 a 的格式String日期从EEEE MMMM d to MM/d/yyyy首先,将其转换为LocalDate然后应用不同模式的格式化程序LocalDate在将其解析为String again.

这是我的代码:

private String convertDate(String stringDate) 
{
    //from EEEE MMMM d -> MM/dd/yyyy

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .append(DateTimeFormatter.ofPattern("EEEE MMMM d"))
            .toFormatter();

    LocalDate parsedDate = LocalDate.parse(stringDate, formatter);
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/d/yyyy");

    String formattedStringDate = parsedDate.format(formatter2);

    return formattedStringDate;
}

但是,我收到了一条我不太理解的异常消息:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'TUESDAY JULY 25' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfWeek=2, MonthOfYear=7, DayOfMonth=25},ISO of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)

正如其他答案已经说过的那样,创建一个LocalDate你需要year,它不在输入中String。它只有day, month and 一周中的天.

为了得到完整的LocalDate,你需要解析day and month并找到一个year其中这个日/月组合匹配一周中的天.

当然你可以忽略一周中的天并假设日期始终为当前日期year;在这种情况下,其他答案已经提供了解决方案。但如果你想找到year完全匹配一周中的天,你必须循环直到找到它。

我还创建了一个格式化程序java.util.Locale,明确我想要的month and 星期几英文名字。如果您不指定区域设置,它将使用系统的默认设置,并且不能保证始终为英语(并且可以在不通知的情况下更改,即使在运行时也是如此)。

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .parseCaseInsensitive()
    .append(DateTimeFormatter.ofPattern("EEEE MMMM d"))
    // use English Locale to correctly parse month and day of week
    .toFormatter(Locale.ENGLISH);
// parse input
TemporalAccessor parsed = formatter.parse("TUESDAY JULY 25");
// get month and day
MonthDay md = MonthDay.from(parsed);
// get day of week
DayOfWeek dow = DayOfWeek.from(parsed);
LocalDate date;
// start with some arbitrary year, stop at some arbitrary value
for(int year = 2017; year > 1970; year--) {
    // get day and month at the year
    date = md.atYear(year);
    // check if the day of week is the same
    if (date.getDayOfWeek() == dow) {
        // found: 'date' is the correct LocalDate
        break;
    }
}

在此示例中,我从 2017 年开始,尝试查找直到 1970 年的日期,但您可以适应适合您的用例的值。

您还可以通过使用获取当前年份(而不是某些固定的任意值)Year.now().getValue().

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java:无法从 TemporalAccessor 获取 LocalDate 的相关文章

随机推荐