-1

I am retrieving time values from SQLServer which are displayed as 0.0833333333333333, while it originally is 02:00 in 24 hour format. Now, I need to convert this decimal value 0.0833333333333333 to 02:00 to do further coding. Is there any direct/simple way to do it in JAVA?

  • Multiply by 24? Maybe round and account for the fractional parts separately if you are wanting minutes rather than fractional parts of an hour. – JMoravitz Aug 05 '20 at 21:39
  • Maybe multiply by 24*60*60, to have the value in seconds, or multiply that by 1000 to have the value in milliseconds. What data type do you want to store this in? If you need a Date, you may need to account for time zones, thing like that. – Marcio Lucca Aug 05 '20 at 21:58
  • I need time in 24 hours format. For e.g. 0.0826388888888889 = 01:59 – Apurva Jain Aug 05 '20 at 22:18

2 Answers2

1

Here is an example, using a 12 hour format, with AM/PM, but using java.time classes:

// no offset, no time zone:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

...

double d = 0.7826388888888889;
long nanos = Math.round(d * 24L * 60L * 60L * 1_000_000_000L);
LocalTime localTime = LocalTime.ofNanoOfDay(nanos);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a");
System.out.println(localTime.format(formatter));

This example prints the following:

6:47 PM

If you prefer, you can use "h:mma" to get 6:47PM - with no space.

LocalTime holds a time value without any time zone information.

You can see a list of the available formatting options here.

Update

As Ole V.V. points out, you can make the code clearer by simplifying the multiplication. Use java.time.Duration or java.util.concurrent.TimeUnit:

long nanosInOneDay = java.time.Duration.ofDays(1).toNanos();

or

long nanosInOneDay = java.util.concurrent.TimeUnit.DAYS.toNanos(1);
andrewJames
  • 19,570
  • 8
  • 19
  • 51
0

Here is an example:

double d = 0.0833333333333333;
Date date = new Date(Math.round(d * 24L * 60L * 60L * 1000L));
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(format.format(date));
Marcio Lucca
  • 370
  • 2
  • 10
  • Works perfectly fine! Thanks so much :) – Apurva Jain Aug 05 '20 at 22:21
  • 1
    Avoid the old and problematic `Date` and `SimpleDateFormat` classes wherever possible, and instead use the newer `java.time` classes, such as `java.time.format.DateTimeFormatter`. See [here](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion/4216767#4216767) and [here](https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime) for background. – andrewJames Aug 05 '20 at 22:23
  • @Marcio Lucca how can I use the same for 12 hour format with AM/PM displayed with it? – Apurva Jain Aug 05 '20 at 22:38