98

I need to convert minutes to hours and minutes in Java. For example 260 minutes should be 4:20.

Can anyone help me how to do such conversion?

informatik01
  • 16,038
  • 10
  • 74
  • 104
lakshmi
  • 4,539
  • 17
  • 47
  • 55

15 Answers15

225

If your time is in a variable called t :

int hours   = t / 60;   // since both are ints, you get an int
int minutes = t % 60;
System.out.printf("%d:%02d", hours, minutes);

It couldn't get easier.


Addendum from 2021

Please notice that this answer is about the literal meaning of the question: how to convert an amount of minute to hours + minutes. It has nothing to do with time, time zones, AM/PM etc.

If you need better control about this kind of stuff, i.e. you're dealing with moments in time and not just an amount of minutes and hours, see Basil Bourque's answer below.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • Is there any way to achieve this with Java 8 `Duration`? – IgorGanapolsky Oct 15 '15 at 15:14
  • 3
    If `t` can be `<0` (negative) then the second line should be `int minutes = Math.abs(t) % 60;`. – wittich Apr 25 '18 at 06:59
  • 1
    and also if you want am or pm with time add this condition String amOrPm; if (timeInminutes>=720) amOrPm="PM"; else amOrPm="AM"; String convertedTime=hours +":" +minutes+amOrPm; – SFAH Jun 26 '18 at 07:35
  • What to do with non-AM/PM locales? This is only partial, non localized solution. – ror May 22 '19 at 16:54
42

tl;dr

Duration.ofMinutes( 260L )
        .toString()

PT4H20M

… or …

LocalTime.MIN.plus( 
    Duration.ofMinutes( 260L ) 
).toString()

04:20

Duration

The java.time classes include a pair of classes to represent spans of time. The Duration class is for hours-minutes-seconds, and Period is for years-months-days.

Duration d = Duration.ofMinutes( 260L );

Duration parts

Access each part of the Duration by calling to…Part. These methods were added in Java 9 and later.

long days = d.toDaysPart() ;
int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;
int seconds = d.toSecondsPart() ;
int nanos = d.toNanosPart() ;

You can then assemble your own string from those parts.

ISO 8601

The ISO 8601 standard defines textual formats for date-time values. For spans of time unattached to the timeline, the standard format is PnYnMnDTnHnMnS. The P marks the beginning, and the T separates the years-month-days from the hours-minutes-seconds. So an hour and a half is PT1H30M.

The java.time classes use ISO 8601 formats by default for parsing and generating strings. The Duration and Period classes use this particular standard format. So simply call toString.

String output = d.toString(); 

PT4H20M

For alternate formatting, build your own String in Java 9 and later (not in Java 8) with the Duration::to…Part methods. Or see this Answer for using regex to manipulate the ISO 8601 formatted string.

LocalTime

I strongly suggest using the standard ISO 8601 format instead of the extremely ambiguous and confusing clock format of 04:20. But if you insist, you can get this effect by hacking with the LocalTime class. This works if your duration is not over 24 hours.

LocalTime hackUseOfClockAsDuration = LocalTime.MIN.plus( d );
String output = hackUseOfClockAsDuration.toString();

04:20


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    Nice, I'm looking for something like this, but I'd like to get the result as "4h 20m" or "4h 20min" rather than "PT4H20M" or "04:20". I guess I'll have to use some kind of formatting method? – aditsu quit because SE is EVIL Jul 19 '17 at 15:17
  • @aditsuquitbecauseSEisEVIL Java 9 brought the `Duration::to…Part` methods shown my edits to this Answer. You can easily assemble your own string from those parts. – Basil Bourque Jun 02 '20 at 05:06
15

Use java.text.SimpleDateFormat to convert minute into hours and minute

SimpleDateFormat sdf = new SimpleDateFormat("mm");

try {
    Date dt = sdf.parse("90");
    sdf = new SimpleDateFormat("HH:mm");
    System.out.println(sdf.format(dt));
} catch (ParseException e) {
    e.printStackTrace();
}
Nikhil Sahu
  • 2,463
  • 2
  • 32
  • 48
Athar Iqbal
  • 458
  • 3
  • 12
14

You can also use the TimeUnit class. You could define

private static final String FORMAT = "%02d:%02d:%02d";
can have a method like:
public static String parseTime(long milliseconds) {
      return String.format(FORMAT,
              TimeUnit.MILLISECONDS.toHours(milliseconds),
              TimeUnit.MILLISECONDS.toMinutes(milliseconds) - TimeUnit.HOURS.toMinutes(
              TimeUnit.MILLISECONDS.toHours(milliseconds)),
              TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(
              TimeUnit.MILLISECONDS.toMinutes(milliseconds)));
   }
walters
  • 1,427
  • 3
  • 17
  • 28
  • I know it’s a bit longer than the code in the accepted answer, but IMHO it is also clearer. I prefer this. – Ole V.V. Apr 12 '17 at 09:08
4

I use this function for my projects:

 public static String minuteToTime(int minute) {
    int hour = minute / 60;
    minute %= 60;
    String p = "AM";
    if (hour >= 12) {
        hour %= 12;
        p = "PM";
    }
    if (hour == 0) {
        hour = 12;
    }
    return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + " " + p;
}
Shohan Ahmed Sijan
  • 4,391
  • 1
  • 33
  • 39
3

It can be done like this

        int totalMinutesInt = Integer.valueOf(totalMinutes.toString());

        int hours = totalMinutesInt / 60;
        int hoursToDisplay = hours;

        if (hours > 12) {
            hoursToDisplay = hoursToDisplay - 12;
        }

        int minutesToDisplay = totalMinutesInt - (hours * 60);

        String minToDisplay = null;
        if(minutesToDisplay == 0 ) minToDisplay = "00";     
        else if( minutesToDisplay < 10 ) minToDisplay = "0" + minutesToDisplay ;
        else minToDisplay = "" + minutesToDisplay ;

        String displayValue = hoursToDisplay + ":" + minToDisplay;

        if (hours < 12)
            displayValue = displayValue + " AM";
        else
            displayValue = displayValue + " PM";

        return displayValue;
    } catch (Exception e) {
        LOGGER.error("Error while converting currency.");
    }
    return totalMinutes.toString();
Marko
  • 20,385
  • 13
  • 48
  • 64
Priyanka
  • 39
  • 1
3

(In Kotlin) If you are going to put the answer into a TextView or something you can instead use a string resource:

<string name="time">%02d:%02d</string>

And then you can use this String resource to then set the text at run time using:

private fun setTime(time: Int) {
    val hour = time / 60
    val min = time % 60
    main_time.text = getString(R.string.time, hour, min)
}
Anthony Cannon
  • 1,245
  • 9
  • 20
1

Given input in seconds you can transform to format hh:mm:ss like this :

int hours;
int minutes;
int seconds;
int formatHelper;

int input;


//formatHelper maximum value is 24 hours represented in seconds

formatHelper = input % (24*60*60);

//for example let's say format helper is 7500 seconds

hours = formatHelper/60*60;
minutes = formatHelper/60%60;
seconds = formatHelper%60;

//now operations above will give you result = 2hours : 5 minutes : 0 seconds;

I have used formatHelper since the input can be more then 86 400 seconds, which is 24 hours.

If you want total time of your input represented by hh:mm:ss, you can just avoid formatHelper.

I hope it helps.

  • 1
    Doesn't work. If `input` is 7500, then the result is 7500 hours, 5 minutes and 0 seconds, which is obviously wrong. And the question didn't mention seconds at all. – fdermishin Dec 08 '20 at 12:38
  • @fdermishin is correct. [Try it online!](https://tio.run/##ZVFNb8IwDL3nV1iT0MrQaIVgk1Zx2Wl3jtMOgXoQlo8qTgoI8ds7l4YxNiVS7DjvPftlKxv5uK2@2pWWRPB6FHVcarUCCjLw0ThVgZHKZovglV2/f4D0axoeW2UDbFz0VIouNMrGgCkhXDlbpeTTeSPDG@oafSnOV8rWMcAcnmdFwVciz38/Yr29MtFAI3VEUASTaS8FHmuPhDZgxSQXHSFu4PPEP4BsMn14KngPyyQCuJem1ggawz0ByUPqDzY9mNW6rq7UvfD8Zoz8TFqKNPT/6qCrJoo/1XOJm7FuB45zttlZArl0DcJOaQ1rxdHBRZ6Wou58mvRNvMDs4jPHxdXmxYECmrGLYVzzLwVtsx4xgjteox/UJU/IYdmeTu03 "Java (JDK) – Try It Online") – General Grievance Dec 15 '20 at 13:00
1

Here is my function for convert a second,millisecond to day,hour,minute,second

public static String millisecondToFullTime(long millisecond) {
    return timeUnitToFullTime(millisecond, TimeUnit.MILLISECONDS);
}

public static String secondToFullTime(long second) {
    return timeUnitToFullTime(second, TimeUnit.SECONDS);
}

public static String timeUnitToFullTime(long time, TimeUnit timeUnit) {
    long day = timeUnit.toDays(time);
    long hour = timeUnit.toHours(time) % 24;
    long minute = timeUnit.toMinutes(time) % 60;
    long second = timeUnit.toSeconds(time) % 60;
    if (day > 0) {
        return String.format("%dday %02d:%02d:%02d", day, hour, minute, second);
    } else if (hour > 0) {
        return String.format("%d:%02d:%02d", hour, minute, second);
    } else if (minute > 0) {
        return String.format("%d:%02d", minute, second);
    } else {
        return String.format("%02d", second);
    }
}

Testing

public static void main(String[] args) {
    System.out.println("60 => " + secondToFullTime(60));
    System.out.println("101 => " + secondToFullTime(101));
    System.out.println("601 => " + secondToFullTime(601));
    System.out.println("7601 => " + secondToFullTime(7601));
    System.out.println("36001 => " + secondToFullTime(36001));
    System.out.println("86401 => " + secondToFullTime(86401));
}

Output

60 => 1:00
101 => 1:41
601 => 10:01
7601 => 2:06:41
36001 => 10:00:01
86401 => 1day 00:00:01

Hope it help

Linh
  • 57,942
  • 23
  • 262
  • 279
0
int mHours = t / 60; //since both are ints, you get an int
int mMinutes = t % 60;
System.out.printf("%d:%02d", "" +mHours, "" +mMinutes);
Jigar Patel
  • 1,550
  • 2
  • 13
  • 29
0

Minutes mod 60 will gives hours with minutes remaining.

http://www.cafeaulait.org/course/week2/15.html

Ryre
  • 6,135
  • 5
  • 30
  • 47
0

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
-1
import java.util.Scanner;
public class Time{
    public static void main(String[]args){
        int totMins=0;
        int hours=0;
        int mins=0;
    Scanner sc= new Scanner(System.in);
    System.out.println("Enter the time in mins: ");
        totMins= sc.nextInt();
        hours=(int)(totMins/60);
        mins =(int)(totMins%60);
        System.out.printf("%d:%d",hours,mins);
    }
}
-1
long d1Ms=asa.getTime();   
long d2Ms=asa2.getTime();   
long minute = Math.abs((d1Ms-d2Ms)/60000);   
int Hours = (int)minute/60;     
int Minutes = (int)minute%60;     
stUr.setText(Hours+":"+Minutes); 
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
developer
  • 9,116
  • 29
  • 91
  • 150
-1

Try this code:

import java.util.Scanner;

public class BasicElement {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int hours;
        System.out.print("Enter the hours to convert:");
        hours =input.nextInt();
        int d=hours/24;
        int m=hours%24;
        System.out.println(d+"days"+" "+m+"hours");     

    }
}
talonmies
  • 70,661
  • 34
  • 192
  • 269