當嘗試將給定日期轉換為特定格式時,Java 開發人員可能會遇到異常: “java.lang.IllegalArgumentException:無法將給定物件格式化為日期。”當嘗試將不受支援的物件格式化為日期時,會出現此錯誤。
要解決此問題,我們需要使用正確的格式化策略。 DateFormat.format 方法接受 Date 物件作為輸入。在提供的範例中,輸入值是表示日期的字串,而不是 Date 物件。
解決方案是使用兩個單獨的 SimpleDateFormat 物件:一個用於解析輸入字串,另一個用於格式化結果。例如:
// Define the output format (mm/yyyy for months and years)
DateFormat outputFormat = new SimpleDateFormat("mm/yyyy", Locale.US);
// Define the input format (yyyy-MM-dd'T'HH:mm:ss.SSSX)
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);
String inputText = "2012-11-17T00:00:00.000-05:00";
try {
// Parse the input string as a Date object
Date date = inputFormat.parse(inputText);
// Format the Date object using the desired format
String outputText = outputFormat.format(date);
} catch (ParseException e) {
// Handle parsing exceptions here
}
透過遵循此方法,我們可以有效地將表示日期的字串轉換為所需的格式,同時避免「無法將給定物件格式化為日期」錯誤。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3