Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hours in decimal format

Tags:

java

I've tried mutliple solutions to this problem but I can't seem to get it.

I have time in decimal format, which is in hours. I want to make it much cleaner by changing it into a DD:HH:MM:SS format.

Example:

10.89 hours == 10 hours, 53 minutes, 40 seconds

EDIT: 10.894945454545455 == 10 hours, 53 minutes, 40 seconds

What I've tried:

int hours = (int) ((finalBuildTime) % 1);
int minutes = (int) ((finalBuildTime * (60*60)) % 60);
int seconds = (int) ((finalBuildTime * 3600) % 60);

return String.format("%s(h) %s(m) %s(s)", hours, minutes, seconds);

Which returned: 0(h) 41(m) 41(s)

Any suggestions?

like image 938
KyleCrowley Avatar asked Jul 14 '14 21:07

KyleCrowley


3 Answers

  1. There is no need to do a modular on minutes.
  2. Your calculation of minutes should just multiply by 60, not (60*60)

    double finalBuildTime = 10.89;
    int hours = (int) finalBuildTime;
    int minutes = (int) (finalBuildTime * 60) % 60;
    int seconds = (int) (finalBuildTime * (60*60)) % 60;
    
    System.out.println(String.format("%s(h) %s(m) %s(s)", hours, minutes, seconds));
    

This code gives you the correct output

10(h) 53(m) 24(s)

I believe your expected output of 40 seconds is incorrect. It should be 24 seconds.

(53*60 + 24)/(60*60) = 0.89
like image 111
JustinKSU Avatar answered Sep 28 '22 08:09

JustinKSU


Here is a complete implementation:

package test.std.java;

public class Test {

    public static void main(String[] args) {
        System.out.println(GetReadableTime(10.89));
    }

    //Prints outs HH:MM:SS
    public static String GetReadableTime(double finalBuildTime){

        int hours = (int) Math.floor(finalBuildTime);
        int remainderInSeconds = (int)(3600.0* (finalBuildTime - Math.floor(finalBuildTime)) );
        int seconds = remainderInSeconds % 60;
        int minutes = remainderInSeconds / 60;
        return  String.format("%02d:%02d:%02d", hours, minutes, seconds); 
    }
}
like image 43
epichorns Avatar answered Sep 28 '22 07:09

epichorns


First part of rgettman is true :

float finalBuildTime = 10.89;
int hours = (int) finalBuildTime; // 10 ok

But (int) ((10.89 * (60 *60)) / 60) = 683 which is not what you want : it is the direct conversion of finalBuildTime in minutes

int minutes = (int) ((finalBuildTime - hours) * 60); // 53 ok
int seconds = (int) ((finalBuildTime - hours) * 3600 - minutes * 60 + 0.5); // 24 ok

I've added 0.5 for the seconds computation to round to the nearest second rather than truncate. For your example it is no use because your time is an integer number of seconds.

And the number of seconds is 24 seconds = 0.4 minutes

like image 28
Serge Ballesta Avatar answered Sep 28 '22 08:09

Serge Ballesta