5

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!

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
bEtTy Barnes
  • 195
  • 1
  • 2
  • 10
  • What is `time` representing? What units is it in? Mayan Long Count units? – ifly6 May 18 '18 at 20:59
  • 1
    You might find it helpful to learn about generating and parsing standard [ISO 8601 strings for durations](https://en.wikipedia.org/wiki/ISO_8601#Durations) using the [`java.time.Duration`](https://docs.oracle.com/javase/10/docs/api/javafx/util/Duration.html) class. – Basil Bourque May 18 '18 at 21:46
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 19 '18 at 00:12
  • @ifly6 minutes bro – bEtTy Barnes May 19 '18 at 13:57
  • Possible duplicate of [How to convert Milliseconds to “X mins, x seconds” in Java?](https://stackoverflow.com/questions/625433/how-to-convert-milliseconds-to-x-mins-x-seconds-in-java) There are many other similar questions and answers, please use your search engine. – Ole V.V. May 20 '18 at 08:15

4 Answers4

9

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • thanks for this! But the requirement is not to use any library. I will use this sample you provided in my production apps instead. – bEtTy Barnes May 19 '18 at 13:58
  • 2
    @bEtTyBarnes What library? How is using this any different from using `SimpleDateFormat`? It's part of the core API – MadProgrammer May 19 '18 at 22:04
  • @bEtTyBarnes Please explain that requirement more precisely in your question. It seems to be an important restriction. How about the built-in standard libraries in Java? – Ole V.V. May 20 '18 at 08:21
  • If i18n is important I recommend using a Locale-aware formatter such as `DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault())` – gb96 Nov 03 '19 at 02:03
  • @gb96 Agreed, that wold by one of the more important reasons for using a formatter - but I'm not aware if `DateFormat` supports formatting duration (because, what's 28hrs anyway?) – MadProgrammer Nov 03 '19 at 20:48
2
int minutes = 160;

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

String.format("%d hr %d mins",h,m); // output : 2 hr 40 mins
Sriram Umapthy
  • 678
  • 8
  • 11
-1

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."

modmoto
  • 2,901
  • 7
  • 29
  • 54
-1

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.";
}
Niki E. Z.
  • 19
  • 1
  • 3
  • 1
    Rolling your own date-time code is generally poor advice. We have the excellent *java.time* classes available; use them. See the [correct Answer by MadProgrammer](https://stackoverflow.com/a/50419562/642706). – Basil Bourque May 18 '18 at 21:40