user4567570 - 6 months ago 23
Java Question

# Calculate the number of days, hours and minutes from total minutes

I;m looking to convert minutes into the days 1 hours and Minutes. I don't want to use

`%`
operator, because the same code I want to use in Apex Salesforce where
`%`
is not supported.

I have developed the code below, but it's not working properly. I need to show the maximum number of days, hours should be less that 24, and Minutes should be less that 60.

``````public class Test {
public static void main(String[] args) {
Integer inputs = 40000;
Integer oneDayMin = 60 * 24;
Integer noOfhr = 0;
Integer minutes = 0;
Integer days = 0;

if(inputs > 0){
noOfhr = inputs /60;
System.out.println("No of hours :: "+noOfhr);

if(noOfhr > 24){
days = noOfhr / 24;
System.out.println("Days : "+days);
minutes = noOfhr - ((noOfhr / 24) * 24);
System.out.println("noOfMinutesleftfromhr : "+minutes);
}
}
String result = null;
if(days > 0)
result = days+" Days ";
if(noOfhr > 0)
result = days+" Days, "+noOfhr+" Hour, ";
if(minutes > 0)
result = days+" Days, "+noOfhr+" Hour, "+minutes+" Minutes";

System.out.println("RESULT :: "+result);
}
}
``````

The output is:

``````RESULT :: 27 Days, 666 Hour, 18 Minutes
``````

Which is not correct.

Answer Source

You were somewhat on the right track, but you forgot to actually remove the days before you calculate the hours:

``````public static void main(String[] args) {
int inputs = 40000;
int days = 0;
int hours = 0;
int minutes = 0;
String result = "";

if(inputs > 1440){
days = inputs / 1440;
inputs = inputs - (days * 1440);
}

if(inputs > 60){
hours = inputs / 60;
inputs = inputs - (hours * 60);
}

if(inputs > 0){
minutes = inputs;
}

if(minutes > 0){
result = days+" Days, "+hours+" Hours, "+minutes+" Minutes";
}else if(hours > 0){
result = days+" Days, "+hours+" Hours";
}else{
result = days+" Days ";
}

System.out.println("RESULT :: "+result);
}
``````

Edit: Removed modulus

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download