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);
}
How would I go about formatting 34658.00 as 03:46:58?
This prints
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:Output:
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
to specify a fractional part (even an optional fractional part) with anything between 0 and 9 decimals.String.replaceFirst
with a regular expression to remove the fractional part, and then also remove it from the format pattern string.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.Since the time is always in UTC, you may want to use
atOffset
to convert theLocalTime
into anOffsetTime
withZoneOffset.UTC
. If you know the date too, anOffsetDateTime
or anInstant
would be appropriate, but I haven’t delved enough into the documentation to find out whether you know the date.Links
java.time
.Then zero-pad and add in ':'s in between. You could truncate or round to whole seconds too, if you wish, but then be careful about seconds rounding up to 60, in which case you have to zero the seconds, add 1 to the minutes, and then possible do it over if you get 60 minutes and round up the hours.