英文:
How to convert decimal value to 24 hour time format in JAVA
问题
我从SQLServer中检索时间值,这些值显示为0.0833333333333333,而原始格式是24小时制的02:00。现在,我需要将这个小数值0.0833333333333333转换为02:00,以进行进一步的编码。在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?
答案1
得分: 1
以下是翻译好的部分:
这是一个示例,使用12小时制,带有AM/PM,但使用java.time
类:
// 没有偏移,没有时区:
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));
这个示例会打印出以下结果:
6:47 PM
如果您喜欢,可以使用"h:mma"
来获取6:47PM
- 没有空格。
LocalTime
保存了一个没有任何时区信息的时间值。
您可以在这里查看可用的格式选项列表:这里。
更新
正如Ole V.V.指出的那样,您可以通过简化乘法来使代码更清晰。使用java.time.Duration
或java.util.concurrent.TimeUnit
:
long nanosInOneDay = java.time.Duration.ofDays(1).toNanos();
或者
long nanosInOneDay = java.util.concurrent.TimeUnit.DAYS.toNanos(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);
答案2
得分: 0
以下是一个示例:
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));
英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论