how to convert minutes to days,hours,minutes
Java-9 java.time
Solution:
import java.time.Duration;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(minutesToDaysHoursMinutes(10080));
System.out.println(minutesToDaysHoursMinutes(1600));
}
public static String minutesToDaysHoursMinutes(int time) {
Duration d = Duration.ofMinutes(time);
long days = d.toDaysPart();
long hours = d.toHoursPart();
long minutes = d.toMinutesPart();
return String.format("%d Day(s) %d Hour(s) %d Minute(s)", days, hours, minutes);
}
}
Output:
7 Day(s) 0 Hour(s) 0 Minute(s)
1 Day(s) 2 Hour(s) 40 Minute(s)
Java-8 java.time
Solution:
import java.time.Duration;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(minutesToDaysHoursMinutes(10080));
System.out.println(minutesToDaysHoursMinutes(1600));
}
public static String minutesToDaysHoursMinutes(int time) {
Duration d = Duration.ofMinutes(time);
long days = d.toDays();
long hours = d.toHours() % 24;
long minutes = d.toMinutes() % 60;
return String.format("%d Day(s) %d Hour(s) %d Minute(s)", days, hours, minutes);
}
}
Output:
7 Day(s) 0 Hour(s) 0 Minute(s)
1 Day(s) 2 Hour(s) 40 Minute(s)
Learn about the modern date-time API from Trail: Date Time.
If you want to do this yourself, go the other way.
- Divide the number by 60 * 24. (That will get the number of days.)
- Divide the remainder by 60. (That will give you number of hours.)
- The remainder of #2 is the number of minutes.
If you use Java 6, TimeUnit enum can be useful. For example:
TimeUnit.HOURS.convert(10, TimeUnit.DAYS)
This static call converts 10 days into hour units, and returns 240. You can play with time units starting from NANOSECONDS and ending with DAYS.
Actually TimeUnit is available from Java 5, but in version 6 more units were added.
--EDIT-- Now that I understand better your question, use the division and remainder approach as in the response of Romain. My tip is useful only for conversion to a single time unit.
A shorter way. (Assumes time >= 0)
public String timeConvert(int time) {
return time/24/60 + ":" + time/60%24 + ':' + time%60;
}