我試圖決議兩個不同的日期并計算它們之間的差異,但出現下一個錯誤:
java.time.format.DateTimeParseException: 無法在索引 2 處決議文本“103545”
這是代碼:
String thisDate= mySession.getVariableField(myVariable).toString().trim();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
LocalDate theDate= LocalDate.parse(thisDate, formatter);
uj5u.com熱心網友回復:
這里的問題是日期決議器必須接收指定格式的日期(在這種情況下為“ddMMyyyy”)
例如,這是決議器回傳有效日期所需的輸入:
String thisDate = '25Sep2000';
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
LocalDate theDate = LocalDate.parse(thisDate, formatter);
我認為您想要的是將以毫秒為單位的日期轉換為具有特定格式的日期。這是你可以做的:
//Has to be made long because has to fit higher numbers
long thisDate = 103545; //Has to be a valid date in milliseconds
DateFormat formatter = new SimpleDateFormat("ddMMyyyy"); //You can find more formatting documentation online
Date theDate = new Date(thisDate);
String finalDate = formatter.format(theDate);
uj5u.com熱心網友回復:
這是預期的(大約)。
您的格式模式字串ddMMyyyy指定月份的兩位數、月份的兩位數和(至少)四位數的年份,總共(至少)八 (8) 位數字。所以當你給它一個只包含 6 位數字的字串時,決議必然會失敗。
如果您的用戶或其他系統需要以ddMMyyyy格式為您提供日期并且他們給了您103545,則他們正在犯錯誤。您的驗證發現了錯誤,這是一件好事。您可能希望讓他們有機會再試一次,并為您提供一個字串,例如10112021(2021 年 11 月 10 日)。
如果(只是猜測)103545是為了表示一天中的時間,10:35:45,那么您需要使用LocalTime該類,并且您還需要更改格式模式字串以指定小時、分鐘和秒而不是年,月份和日期。
String thisDate = "103545";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
LocalTime theTime = LocalTime.parse(thisDate, formatter);
System.out.println(theTime);
這個片段的輸出是:
10:35:45
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/355820.html
上一篇:如何在Python中將UTC日期時間轉換為本地日期時間(澳大利亞/墨爾本)
下一篇:需要從輸入xml減少20天之前
