簡體   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