Formatting a number of minutes into time

134 views Asked by At

So I have a variable time. It counts the minutes. Is there a way I can format this into minutes easily? For example, time = 63

would equal

1:03

and time = 605

would equal

10:05.

Thank you in advance!

6

There are 6 answers

0
Jeroen Vannevel On
public static void main(String[] args) {
    Calendar cal = new GregorianCalendar();
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    cal.add(Calendar.MINUTE, 605);
    System.out.println(cal.getTime());
}

Simply create a new Calendar and add the amount of minutes. You don't need the date part, just the time. For this reason I reset everything manually in the calendar. By using a Calendar you also have a lot more flexibility with other date-appropriate calculations.

Output:

Thu Dec 05 10:05:00 CET 2013

0
Masudul On

Try,

int  totSec= 605;

int min=totSec/60;
int second=totSec%60;
System.out.printf("%d:%02d\n",min,second);
0
Archimedes Trajano On

SimpleDateFormat can render any time format you want including the above.

For the Date object you just need to set it to the number of milliseconds since epoch http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(long)

new SimpleDateFormat("HH:mm").format(new Date(minutes * 1000 * 60))

The only problem with the solution above is if time is past 23:59 it will roll over.

0
Vikdor On

Assuming that the input is always in seconds:

System.out.println(
    new SimpleDateFormat("HH:mm:ss").format(
        new SimpleDateFormat("ss").parse("" + seconds)));
0
Evgeniy Dorofeev On

try this

String s = String.format("%02d:%02d", time / 60, time % 60);
0
sijeesh On
 minsformat(305);

public void minsformat(int m){
int hour=m/60;
int s=m%60;

system.out.println(hour+":"+s);
}