我想將 LocalDateTime 決議2021-11-24T15:11:38.395為 LocalDateTime 2021-11-24T15:11:38.39。但是 LocalDateTime.parse() 最后總是加零,忽略我的模式。
public class DateTimeFormatUtils {
private static final String ISO_DATE_TIME = "yyyy-MM-dd'T'HH:mm:ss.SS";
public static LocalDateTime formatToISO(final LocalDateTime localDateTime) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(ISO_DATE_TIME);
return LocalDateTime.parse(formatter.format(localDateTime), formatter);
}
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
System.out.println(formatToISO(now));
}
}
輸出:
2021-11-30T11:48:28.449195200
2021-11-30T11:48:28.440
有沒有辦法處理這個問題?
uj5u.com熱心網友回復:
請注意,字串“2021-11-24T15:11:38.39”和“2021-11-24T15:11:38.39 0 ”表示相同LocalDateTime。從技術上講,您已經獲得了預期的輸出!
既然你說輸出不是你期望的,你實際上期望 aString作為輸出,因為 "2021-11-24T15:11:38.39" 和 "2021-11-24T15:11:38.390" 是不同的字串。formatToISO應該回傳一個字串 - 你不應該將格式化的日期決議回LocalDateTime:
public static String formatToISO(final LocalDateTime localDateTime) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(ISO_DATE_TIME);
return formatter.format(localDateTime);
}
這類似于初學者列印doubles 并期望他們用來分配給變數的特定格式的常見錯誤。
double d = 5;
System.out.println(d); // expected 5, actual 5.0
LocalDateTime,就像double,不存盤任何關于它應該如何格式化的資訊。它只存盤一個value,并且相同的 value 將以相同的方式格式化。
uj5u.com熱心網友回復:
Java 秒數總是回傳 3 位數字。
解決方法是,首先將 LocalDateTime 轉換為 String,然后洗掉字串的最后一個字符。
當然,請驗證空檢查。
private static String removeLastDigit(String localDateTime) {
return localDateTime.substring(0, localDateTime.length()-1);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/370512.html
