androidtimedatetimeofday

Time without date


I get time with time zone (without date component) from a PostgreSQL server in json like this { "time": "03:00:00+01" }. How do I handle this in Android? Is there any structure which can hold just time without date? Or converting it to the epoch Date representation i.e. Thu Jan 01 03:00:00 GMT+01:00 1970 is the only good solution?


Solution

  • OffsetTime from java.time and ThreeTenABP

    An OffsetTime is a time of day without date and with an offset from UTC. It thus very precisely models the information in your string from JSON. So I would clearly prefer it over Date. Also because the Date class is poorly designed and long outdated.

        String timeStringFromJson = "03:00:00+01";
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ssX");
        OffsetTime parsedTime = OffsetTime.parse(timeStringFromJson, timeFormatter);
        System.out.println("Parsed time: " + parsedTime);
    

    Output from this snippet is:

    Parsed time: 03:00+01:00

    As a detail that may or may not matter to you, the offset from the string is retained, contrary to what Date can do because a Date hasn’t got a time zone or offset.

    Question: Doesn’t java.time require Android API level 26?

    java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

    Links