問題描述
我需要像這樣格式化我的時間字符串:
I need to format my time string such as this:
int time = 160;
這是我的示例代碼:
public static String formatDuration(String minute) {
String formattedMinute = null;
SimpleDateFormat sdf = new SimpleDateFormat("mm");
try {
Date dt = sdf.parse(minute);
sdf = new SimpleDateFormat("HH mm");
formattedMinute = sdf.format(dt);
} catch (ParseException e) {
e.printStackTrace();
}
return formattedMinute;
// int minutes = 120;
// int h = minutes / 60 + Integer.parseInt(minute);
// int m = minutes % 60 + Integer.parseInt(minute);
// return h + "hr " + m + "mins";
}
我需要將其顯示為 2 小時 40 分鐘.但我不知道如何附加小時"和分鐘".要求是不要使用任何庫.
I need to display it as 2hrs 40mins. But I don't have a clue how to append the "hrs" and "mins". The requirement is not to use any library.
如果您過去做過類似的事情,請隨時提供幫助.非常感謝!
If you've done something like this in the past, feel free to help out. Thanks a bunch!
推薦答案
既然是 2018 年,你真的應(yīng)該使用 Java 8 中引入的日期/時間庫
Since, it's 2018, you really should be making use of the Date/Time libraries introduced in Java 8
String minutes = "160";
Duration duration = Duration.ofMinutes(Long.parseLong(minutes));
long hours = duration.toHours();
long mins = duration.minusHours(hours).toMinutes();
// Or if you're lucky enough to be using Java 9+
//String formatted = String.format("%dhrs %02dmins", duration.toHours(), duration.toMinutesPart());
String formatted = String.format("%dhrs %02dmins", hours, mins);
System.out.println(formatted);
哪些輸出...
2hrs 40mins
為什么要使用這樣的東西?除了通常是更好的 API,當(dāng) minutes
等于 1600
時會發(fā)生什么?
Why use something like this? Apart of generally been a better API, what happens when minutes
equals something like 1600
?
上面將顯示 26hrs 40mins
,而不是打印 2hrs 40mins
.SimpleDateFormat
格式化日期/時間值,它不處理持續(xù)時間
Instead of printing 2hrs 40mins
, the above will display 26hrs 40mins
. SimpleDateFormat
formats date/time values, it doesn't deal with duration
這篇關(guān)于Java 格式小時和分鐘的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!