Java format hour and min

2019-01-27 01:31发布

I need to format my time string such as this:

int time = 160;

Here's my sample code:

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";
}

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!

4条回答
小情绪 Triste *
2楼-- · 2019-01-27 01:50

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);

Which outputs...

2hrs 40mins

Why use something like this? Apart of generally been a better API, what happens when minutes equals something like 1600?

Instead of printing 2hrs 40mins, the above will display 26hrs 40mins. SimpleDateFormat formats date/time values, it doesn't deal with duration

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-27 01:53

Just try

sdf = new SimpleDateFormat("HH 'hrs' mm 'mins'");

There is a good documentation https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html From the doc:

"Text can be quoted using single quotes (') to avoid interpretation."

查看更多
三岁会撩人
4楼-- · 2019-01-27 02:05

Get the string you're making and split it by whatever character is separating the values, i.e ' ', or ':'

Then do

String[] results = result.split(' ');
result = results[0] + " hrs " + results[1] + " minutes ";
查看更多
Bombasti
5楼-- · 2019-01-27 02:08

Another simple approach could be something along the lines:

public static String formatDuration(String minute){
    int minutes = Integer.parseInt(minute);

    int hours = minutes / 60;
    minutes = minutes % 60;

    return hours + "hrs " + minutes + "mins.";
}
查看更多
登录 后发表回答