簡體   English   中英

字符串日期到本地日期的轉換

[英]String Date to LocalDate conversion

我的應用程序提供日期格式,我正在嘗試將該字符串轉換為 LocalDate。這是我的代碼

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

public class DateStringUtil {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");
        //SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        String date ="26 Aug 2019 09:46:09,469";
        LocalDate ld = LocalDate.parse(date, dtf);


    }

}

我收到錯誤。 任何想法如何解決它。

Exception in thread "main" java.time.format.DateTimeParseException: Text '26 Aug 2019 09:46:09,469' could not be parsed at index 2
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)
at src.DateStringUtil.main(DateStringUtil.java:24)

您的日期時間格式與輸入日期不匹配:

  • 您的格式需要dd/MM/yyyy hh:mm模式中的日期: 26/08/2019 09:46
  • 您的日期字符串是dd MMM yyyy hh:mm:ss,SSS模式中的日期: 26 Aug 2019 09:46:09,469

Java DateTimeFormatter文檔提供了有關您可以使用的模式的更多信息: https : //docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

編輯:如果您想以不同的格式輸出本地日期,請創建第二個DateTimeFormatter並將其傳遞給format方法。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateStringUtil {
    public static void main(String[] args) {
        DateTimeFormatter inputDtf = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss,SSS");
        String date = "26 Aug 2019 09:46:09,469";
        LocalDateTime ld = LocalDateTime.parse(date, inputDtf);

        DateTimeFormatter outputDtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
        String outputDate = ld.format(outputDtf);
    }
}

您輸入的日期應與DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");指定的格式相同DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");

    public static void main(String args[]) {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");
    //SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
    String date ="26/08/2019 09:46";
    LocalDate ld = LocalDate.parse(date, dtf);

}

您可能需要參考此文檔了解格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM