亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將日期時間數據字符串轉換為 LocalDate?

如何將日期時間數據字符串轉換為 LocalDate?

鴻蒙傳說 2023-06-21 16:04:45
我有一個日期時間信息字符串,我正在嘗試將其轉換為 LocalDate 字段。字符串的內容是“2019-08-28 09:00:00”。我正在嘗試獲取 MM/dd/yyyy LocalDate 值以加載到 JavaFX DatePicker 字段中。我努力了Date date = new SimpleDateFormat("MM/dd/yyyy").parse(stringDate);和DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); LocalDate localDate = LocalDate.parse((CharSequence) date, formatter);兩者都返回了錯誤。選項#2返回的錯誤如下:Caused by: java.time.format.DateTimeParseException: Text '2019-08-30 12:00:00' could not be parsed at index 2     at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)     at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)     at java.time.LocalDate.parse(LocalDate.java:400)     at utils.DateTimeConverter.convertStringDateToLocalDate(DateTimeConverter.java:27)
查看完整描述

2 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

這取決于你想達到什么目的?


如果結果是包含小時、分鐘和秒的日期,則 DateFormatter 比 DateTimeFormatter 更合適


DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

LocalDate localDate = LocalDate.parse(date, formatter);

或者


DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalTimeDate localDateWithTime = LocalTimeDate.parse(date, formatter);

生成該錯誤是因為您想要生成一個不帶(小時、分鐘等)的日期,而使用DateTimeFormatteraLocalDate而不是LocalTimeDate您的模式格式的正確類型。


注意:您不必強制轉換CharSequence為String


編輯 2:


如果您要在日期選擇器中輸入的日期是 2019-08-28,模式應該是yyyy-MM-dd而不是。MM-dd-yyyy


這里的 JUnit 測試證明我在說什么:


@Test

public void testDate() {

    String date = "2019-08-30 12:00:00";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    LocalDateTime localTimeDate = LocalDateTime.parse(date, formatter);

    assertTrue(localTimeDate.toString().equals(date));

}


@Test

public void testDateWithoutTime() {

    String date = "2019-08-30";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    LocalDate localDate = LocalDate.parse(date, formatter);

    assertTrue(localDate.toString().equals(date));

}


查看完整回答
反對 回復 2023-06-21
?
莫回無

TA貢獻1865條經驗 獲得超7個贊

您的模式不包含相關時間信息。你也需要包括它。

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(stringDate);


查看完整回答
反對 回復 2023-06-21
  • 2 回答
  • 0 關注
  • 195 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號