誰能告訴我為什么我在控制臺上收到“10/09/2022”?
String sFecha = "10/21/2021";
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(sdf.format(sdf.parse(sFecha)));
} catch (java.text.ParseException e) {
//Expected execution
}
注意:輸入字串是故意錯誤的 - 我期待例外!
uj5u.com熱心網友回復:
當您這樣做時,sdf.parse()您將文本轉換為日期:
10 -> days
21 -> month
2021 -> year
21 作為月份被轉換為 9(因為21 % 12 = 9)。
使用setLenient(false)它會拋出例外:
通過寬松決議,決議器可以使用試探法來解釋與此物件格式不精確匹配的輸入。使用嚴格決議,輸入必須與此物件的格式匹配。
uj5u.com熱心網友回復:
你的格式是日/月/年。21 不是有效月份,似乎減去 12 以獲得有效月份。
uj5u.com熱心網友回復:
時間
該java.util日期時間API及API格式,SimpleDateFormat都已經過時,而且容易出錯。建議完全停止使用它們并切換到現代 Date-Time API *。
您在代碼中觀察到的問題是您面臨的奇怪問題之一SimpleDateFormat。不是因為格式錯誤而拋出例外,而是 SimpleDateFormat嘗試錯誤地決議日期字串。
使用java.time現代日期時間 API 的解決方案:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Main {
public static void main(String[] args) {
String sFecha = "10/21/2021";
try {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(sFecha, dtf);
System.out.println(date);
} catch (DateTimeParseException e) {
System.out.println("A problem occured while parsing the date string.");
// ...Handle the exception
}
}
}
輸出:
A problem occured while parsing the date string.
現在,將格式更改為MM/dd/yyyy,您將看到日期字串將被成功決議。
從Trail: Date Time 中了解有關現代日期時間 API 的更多資訊。
如果您想使用SimpleDateFormat:
傳遞false到默認SimpleDateFormat#setLenient設定true。
演示:
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
String sFecha = "10/21/2021";
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
System.out.println(sdf.format(sdf.parse(sFecha)));
} catch (java.text.ParseException e) {
System.out.println("A problem occured while parsing the date string.");
// ...Handle the exception
}
}
}
輸出:
A problem occured while parsing the date string.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/333074.html
