如何将双精度值格式化为时间 [英] How to format a double value as time
问题描述
我正在研究一个读取gps数据的程序. NMEA字符串返回的时间如下:34658.00.
I am working on a program that reads gps data. A NMEA string returns time like this: 34658.00.
我的解析器将其视为双精度
My parser treats that as a double
InputLine = "\\$GPGGA,34658.00,5106.9792434234,N,11402.3003,W,2,09,1.0,1048.47,M,-16.27,M,08,AAAA*60";
//NMEA string
//inputLine=input.readLine();
if(inputLine.contains("$GPGGA")) {
String gpsgga = inputLine.replace("\\", "");
String[] gga = gpsgga.split(",");
String utc_time = gga[1];
if (!gga[1].isEmpty()) {
Double satTime = Double.parseDouble(utc_time);
gpsData.setgpsTime(satTime);
}
我该如何将34658.00格式化为03:46:58?
How would I go about formatting 34658.00 as 03:46:58?
推荐答案
DateTimeFormatter nmeaTimeFormatter = DateTimeFormatter.ofPattern("Hmmss.SS");
String utcTime = "34658.00";
System.out.println(LocalTime.parse(utcTime, nmeaTimeFormatter));
此打印
03:46:58
03:46:58
首先解析为double
是绕道而行,它只会为您提供比必要的更为复杂的代码,因此请避免这种情况.就像解析任何其他格式的时间一样,只需解析时间即可.上面的内容也可以在上午10点后的时间工作,但小时数是两位数吗?是的输入:
Parsing into a double
first is the detour, it just gives you more complicated code than necessary, so avoid that. Just parse the time as you would parse a time in any other format. Does the above also work for times after 10 AM where the hours are two digits? It does. Input:
String utcTime = "123519.00";
输出:
12:35:19
12:35:19
尽管它确实需要两个小数(如果它们不为零,则将它们返回).如果小数位数可能有所不同,则至少有两个选项
It does require exactly two decimals, though (and will render them back if they are non-zero). If the number of decimals may vary, there are at least two options
- 使用
DateTimeFormatterBuilder
指定小数部分(甚至是可选的小数部分),其小数位数介于0到9之间. - hack:使用
String.replaceFirst
和正则表达式删除小数部分,然后再将其从格式模式字符串中删除.
- Use a
DateTimeFormatterBuilder
to specify a fractional part (even an optional fractional part) with anything between 0 and 9 decimals. - The hack: use
String.replaceFirst
with a regular expression to remove the fractional part, and then also remove it from the format pattern string.
它还要求小数点前至少5位数字,因此一天中第一个小时的时间必须有前导零,例如00145.00
表示00:01:45.
It also requires at least 5 digits before the decimal point, so times in the first hour of day need to have leading zeroes, for example 00145.00
for 00:01:45.
由于时间始终是UTC,因此您可能想使用atOffset
将LocalTime
转换为带有ZoneOffset.UTC
的OffsetTime
.如果您也知道日期,则OffsetDateTime
或Instant
是合适的,但是我对文档的了解不够深,无法确定您是否知道日期.
Since the time is always in UTC, you may want to use atOffset
to convert the LocalTime
into an OffsetTime
with ZoneOffset.UTC
. If you know the date too, an OffsetDateTime
or an Instant
would be appropriate, but I haven’t delved enough into the documentation to find out whether you know the date.
- Oracle教程:日期时间解释了如何使用
java.time
./li> - NMEA数据
- Oracle tutorial: Date Time explaining how to use
java.time
. - NMEA data
这篇关于如何将双精度值格式化为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!