Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java format hour and min

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!

like image 494
bEtTy Barnes Avatar asked Jan 03 '23 09:01

bEtTy Barnes


2 Answers

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

like image 177
MadProgrammer Avatar answered Jan 09 '23 08:01

MadProgrammer


int minutes = 160;

int h = minutes / 60;
int m = minutes % 60;

String.format("%d hr %d mins",h,m); // output : 2 hr 40 mins
like image 27
Sriram Avatar answered Jan 09 '23 10:01

Sriram