How to format a double value as time

送分小仙女□ 提交于 2019-12-13 04:13:22

问题


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?


回答1:


    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

  • Oracle tutorial: Date Time explaining how to use java.time.
  • NMEA data



回答2:


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.



来源:https://stackoverflow.com/questions/49092348/how-to-format-a-double-value-as-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!