简体   繁体   中英

How to convert decimal value to 24 hour time format in JAVA

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?

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 VV 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);

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM