1

I have String variable movieDuration, which contains value in minutes. Need to convert that to HH:mm format. How should I do it?

Tried to do it as:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
movieDurationFormatted = formatter.format(movieDuration);

But looks like value in minutes is not ok for formatter.

skaffman
  • 398,947
  • 96
  • 818
  • 769
LA_
  • 19,823
  • 58
  • 172
  • 308
  • 1
    A `DateFormat` formats a date, not a duration. For the difference, consult a dictionary. For converting minutes into hours I’d recommend checking said dictionary, look for “division.” – Bombe Mar 26 '11 at 12:31
  • So, are you suggesting manually to divide minutes by 60, take integer part as hours, remainder as minutes? – LA_ Mar 26 '11 at 12:44
  • LA_, of course because that is exactly how it’s done. :) – Bombe Mar 26 '11 at 18:27
  • Convert to a `Duration`, for example `Duration movieDuration = Duration.ofMinutes(97);`. Since Java 9 and probably available on Android through desugaring, format like `String.format(Locale.US, "%d:%02d", movieDuration.toHours(), movieDuration.toMinutesPart())`. In this example the result is `1:37`. – Ole V.V. Feb 09 '23 at 09:27
  • Does this answer your question? [How to convert minutes to Hours and minutes (hh:mm) in java](https://stackoverflow.com/questions/5387371/how-to-convert-minutes-to-hours-and-minutes-hhmm-in-java) – Ole V.V. Feb 09 '23 at 09:31

3 Answers3

15
public static String formatHoursAndMinutes(int totalMinutes) {
    String minutes = Integer.toString(totalMinutes % 60);
    minutes = minutes.length() == 1 ? "0" + minutes : minutes;
    return (totalMinutes / 60) + ":" + minutes;
}
aroth
  • 54,026
  • 20
  • 135
  • 176
1

Just use the following method to convert minutes to HH:mm on android?

if you want to process long value then just change the parameter type

public static String ConvertMinutesTimeToHHMMString(int minutesTime) {
    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
    df.setTimeZone(timeZone);
    String time = df.format(new Date(minutesTime * 60 * 1000L));

    return time;
}

Happy coding :)

Monir Zzaman
  • 459
  • 4
  • 7
1

Solution on kotlin Documentation

import kotlin.time.Duration
import kotlin.time.DurationUnit
import kotlin.time.toDuration

val min = 150.toDuration(DurationUnit.MINUTES)
val time = min.toComponents { days, hours, minutes, seconds, nanoseconds -> 
 "$days $hours $minutes $seconds $nanoseconds"
}

We get 0 days 2 hours 30 minutes 0 seconds 0 nanoseconds

We can also use

DurationUnit.DAYS
DurationUnit.HOURS
DurationUnit.SECONDS
DurationUnit.MILLISECONDS
DurationUnit.MICROSECONDS
DurationUnit.NANOSECONDS
Arman
  • 25
  • 7