我需要像这样格式化我的时间字符串:
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 年,你真的应该使用 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,当 minutes 等于 1600 时会发生什么?
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 格式化日期/时间值,它不处理持续时间
Instead of printing 2hrs 40mins, the above will display 26hrs 40mins. SimpleDateFormat formats date/time values, it doesn't deal with duration
这篇关于Java 格式小时和分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何检测 32 位 int 上的整数溢出?How can I detect integer overflow on 32 bits int?(如何检测 32 位 int 上的整数溢出?)
return 语句之前的局部变量,这有关系吗?Local variables before return statements, does it matter?(return 语句之前的局部变量,这有关系吗?)
如何将整数转换为整数?How to convert Integer to int?(如何将整数转换为整数?)
如何在给定范围内创建一个随机打乱数字的 intHow do I create an int array with randomly shuffled numbers in a given range(如何在给定范围内创建一个随机打乱数字的 int 数组)
java的行为不一致==Inconsistent behavior on java#39;s ==(java的行为不一致==)
为什么 Java 能够将 0xff000000 存储为 int?Why is Java able to store 0xff000000 as an int?(为什么 Java 能够将 0xff000000 存储为 int?)