Search code examples
javaandroidjsonjava-timedatetimeformatter

Conversion from time Duration to time String


I am getting time through JSON in this format "DocTime": "PT18H30M".

How to convert from this format to normal String time e.g. "6:30 pm" in android?

For time being I found this Solution:

    String  json = "PT18H30M";
    System.out.println("Server Time: " +json);
    int h = json.indexOf("H");
    int m = json.indexOf("M");
    int hrs = Integer.valueOf(json.substring(2 , h));
   // System.out.println("hrs: " + hrs);
    int min = Integer.valueOf(json.substring((h+1) , m));
   // System.out.println("min: " + min);
    String shrs = (hrs>12)? String.valueOf((hrs - 12)) : String.valueOf(hrs);
    String mode = (hrs>12)? "pm" : "am";
    
    String fTime = shrs+":"+min+" "+mode;
           
    System.out.println("Normal Time: " +fTime);

Solution

  • Do it as follows:

    With Java-8:

    import java.time.Duration;
    import java.time.LocalTime;
    import java.time.format.DateTimeFormatter;
    
    public class Main {
        public static void main(String[] args) {
            Duration duration = Duration.parse("PT18H30M");
            LocalTime time = LocalTime.of((int) duration.toHours(), (int) (duration.toMinutes() % 60));
            System.out.println(time.format(DateTimeFormatter.ofPattern("h:m a")));
        }
    }
    

    Output:

    6:30 pm
    

    If your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

    With Java-9:

    import java.time.Duration;
    import java.time.LocalTime;
    import java.time.format.DateTimeFormatter;
    
    public class Main {
        public static void main(String[] args) {
            Duration duration = Duration.parse("PT18H30M");
            LocalTime time = LocalTime.of(duration.toHoursPart(), duration.toMinutesPart());
            System.out.println(time.format(DateTimeFormatter.ofPattern("h:m a")));
        }
    }
    

    Output:

    6:30 pm
    

    Note that Duration#toHoursPart and Duration#toMinutesPart were introduced with Java-9.