simba
simba

Reputation: 277

Convert Days to hours:minutes:second java

How can I convert 0.230324074074074 to 05:31:40 in Java? I have code in sql but need in java.

 (select * from(SELECT    TRUNC (
                               (  (X_GSA_LEAVE_SITE - X_GSA_ARRIVE_ONSITE)
                                * 24
                                * 60)
                             / 60)
                       || ':'
                       || (  (  (X_GSA_LEAVE_SITE - X_GSA_ARRIVE_ONSITE)
                              * 24
                              * 60)
                           -   TRUNC (
                                    (  (  X_GSA_LEAVE_SITE
                                        - X_GSA_ARRIVE_ONSITE)
                                     * 24
                                     * 60)
                                  / 60)
                             * 60)

Upvotes: 0

Views: 689

Answers (4)

Scary Wombat
Scary Wombat

Reputation: 44854

Just for fun here is an old fashioned Calendar version

int seconds = (int) (0.230324074074074 * 24 * 60 * 60);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.SECOND, seconds);

String result = String.format("%02d:%02d:%02d", 
            cal.get(Calendar.HOUR),
            cal.get(Calendar.MINUTE),
            cal.get(Calendar.SECOND));
System.out.println(result);

Upvotes: 0

Kartik
Kartik

Reputation: 7917

long seconds = (long) (0.230324074074074 * 24 * 60 * 60);
String result = String.format("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60));
System.out.println(result);

Upvotes: 0

ernest_k
ernest_k

Reputation: 45339

You can convert that fraction of day to a LocalTime using:

LocalTime.ofSecondOfDay((long)(0.230324074074074 * 24 * 60 * 60))

This converts the value to seconds and constructs a LocalTime object. Printing the result outputs "05:31:39" (LocalTime.toString outputs time in your desired format). You may need to control rounding in a different way if you expect exactly 05:31:40)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

It appears that the value 0.230324 is a fraction of a day, and you want to display this as hours:minutes:seconds. There is a fairly straightforward way to do this in Java 8:

double input = 0.230324074074074d;
long seconds = new Double(input*24*60*60).longValue();
System.out.println(LocalTime.MIN.plusSeconds(seconds)
    .format(DateTimeFormatter.ISO_LOCAL_TIME));

05:31:39

Demo

Upvotes: 1

Related Questions