繁体   English   中英

无法正确解析 LocalDate

[英]Can't get LocalDate to Parse correctly

String date = "08/02/2022 Tuesday";
DateTimeFormatter LONG_DATE_FORMAT_ddMMyyyyEEEE = ofPattern("dd/MM/yyyy EEEE");
LocalDate.parse(date, LONG_DATE_FORMAT_ddMMyyyyEEEE);

我收到带有以下消息的 DateTimeParseException:无法在索引 11 处解析文本 08/02/2022 星期二。

我想这是我格式的 EEEE 方面的问题,但我似乎不明白应该用什么来代替它。

这是 java 1.8.0_311

LocalDate 包含日、月和年(在 +999999999-12-31 和 -999999999-12-31 之间变化)

解析拒绝时间和其他值之类的内容。 如果您想要星期几,您可以使用 function,例如:

    // Parses the date
    LocalDate dt = LocalDate.parse("2018-11-27");

    // Prints the day
    System.out.println(dt.getDayOfWeek());

我们需要 DateTimeFormatter class 来正确格式化日期字符串。 我们还需要将字符串日期转换为 LocalDate object 并再次转换回字符串以显示。 DateTimeParseException class 处理任何不希望的结果。

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

class Main {

    public static void main(String[] args) {

    try{

        String date = "08-02-2022 Tuesday";
        DateTimeFormatter pattern = 
            DateTimeFormatter.ofPattern("dd-MM-yyyy eeee");

        // parsing string date to LocalDate obj
        // The part you were missing 
        LocalDate formattedDate = LocalDate.parse(date, pattern);

        // Again converting to string 
        System.out.println(formattedDate.format(pattern));
        }

        // handling exception for unparseble dates
        catch(DateTimeParseException x){
            System.out.println("The given date cannot be parsed");
        }
    }
}

这对我有用:

String date = "08/02/2022 Tuesday";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy EEEE");
    
LocalDate time = LocalDate.parse(date, formatter);
System.out.println(time.format(formatter));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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