關於LocalTime中整分HH:mm:00的處理

今天碰到一個奇怪的問題,從數據庫中讀取兩筆記錄進行轉換時,一筆成功一筆失敗,發現是對一個LocalTime字段進行格式化的時候報錯了,復現如下:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Time {

public static void main(String args[]) {
	try {
		System.out.println("整分數據:");
		LocalTime lt1 = LocalTime.of(14,34,00);
		System.out.println(lt1);
		System.out.println(lt1.toString());
		System.out.println(lt1.format(DateTimeFormatter.ISO_LOCAL_TIME));
		
		System.out.println("非整分數據:");
		LocalTime lt2 = LocalTime.of(14,34,01);
		System.out.println(lt2);
		System.out.println(lt2.toString());
	} catch (Exception e) {
		e.printStackTrace();
	}
 }
}

輸出:
在這裏插入圖片描述
發現了沒,對於整分的數據,LocalTime在輸出的時候會直接忽略末尾的“00”,因此需要使用format進行格式轉換,保留最後兩位,如果還有其他更好的辦法,歡迎留言探討。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章