How to format a double value as time

2019-08-28 05:38发布

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?

2条回答
仙女界的扛把子
2楼-- · 2019-08-28 06:19
    DateTimeFormatter nmeaTimeFormatter = DateTimeFormatter.ofPattern("Hmmss.SS");
    String utcTime = "34658.00";
    System.out.println(LocalTime.parse(utcTime, nmeaTimeFormatter));

This prints

03:46:58

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

Output:

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

  1. Use a DateTimeFormatterBuilder to specify a fractional part (even an optional fractional part) with anything between 0 and 9 decimals.
  2. The hack: use 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 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.

Links

查看更多
乱世女痞
3楼-- · 2019-08-28 06:22
int hours = (int) Math.floor(satTime / 10000);
int minutes = (int) Math.floor((satTime - hours * 10000) / 100);
double seconds = satTime % 100;

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.

查看更多
登录 后发表回答