2013-05-13 28 views
2

我試圖格式化雙表示這樣的時刻:格式十進制表示小時爲HH:MM

Double totalHours = 1.05; 

int hour = totalHours.intValue(); 
Long minutes = Math.round((totalHours - hour) * 60); 

System.out.println(hour + ":" + minutes); 

在這種情況下,我得到"1:3",但我喜歡爾德"01:03"。我將如何做到這一點?

或者有更好的方法來做到這一點?

回答

7

使用DecimalFormat

DecimalFormat df = new DecimalFormat("00"); // "0" means don't omit leading zero 
System.out.println(df.format(hour) + ":" + df.format(minutes)); 
+0

10秒!不錯+1 – christopher 2013-05-13 15:12:17

+0

正是我想要的!謝謝! +1 – LuizAo 2013-05-13 15:21:48

1

試試這個:

String strHourFormat = "HH"; 
SimpleDateFormat sdf = new SimpleDateFormat(strHourFormat); 
sdf = new SimpleDateFormat(strHourFormat); 
2

使用String.format("%02d:%02d", hour, minutes)