Search code examples
androidjsonstringgdata

Android Format String into minutes and seconds


I am parsing YouTube JSON-C GDATA feeds and as it is JSON it can not contain a colon (:) so when I parse the string duration it comes as plain text i.e 823 or 2421. how would I format this to be more readable? i.e 823 --> 8:23 or 2421 --> 24.21 or 23 --> 0:23?


Solution

  • This code should do it:

    String time = "322";
    int length = time.length();
    StringBuffer s = new StringBuffer(time);
    
    switch(length) {
        case(1):    s.insert(0, "0:0"); break; //ex: 2 -> 0:02
        case(2):    s.insert(0, "0:"); break; //ex: 22 -> 0.22
        case(3):    s.insert(1, ":"); break;  //ex: 322 -> 3:22
        case(4):    s.insert(2, ":"); break; //ex: 2421 -> 24:21
    }
    

    And you can continue to add case(5) if you expect a length in hours.

    Good Luck!