【问题标题】:Android Format String into minutes and secondsAndroid 将字符串格式化为分钟和秒
【发布时间】:2012-08-29 13:47:03
【问题描述】:

我正在解析 YouTube JSON-C GDATA 提要,因为它是 JSON,它不能包含冒号 (:),所以当我解析字符串持续时间时,它以纯文本形式出现,即 823 或 2421。我将如何将其格式化为更具可读性?即 823 --> 8:23 或 2421 --> 24.21 或 23 --> 0:23?

【问题讨论】:

    标签: android json string gdata


    【解决方案1】:

    这段代码应该可以做到:

    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
    }
    

    如果您希望以小时为单位,您可以继续添加 case(5)。

    祝你好运!

    【讨论】:

    • 我添加了这样的代码:pastebin.com/ajCVfUYr 但是当我运行它时,它会像这样:imgur.com/N72zi ???
    • 您应该将s 放在地图中,而不是time:map.put(KEY_VIDEODURATIONFORMATTED, s);。我们在s 上进行了插入。
    【解决方案2】:

    我想严格回答你的问题,答案是:

    //Check the length of the string and maybe add zero at the beginning
    string = StringBuffer(string).insert(2, ":").toString();
    

    注意:我应该使用 string.getLength()-2,但我希望你明白了 ;-)

    但是,就我个人而言,我会以秒或其他格式发送时间。

    String dateStr = "03/08/2010"; 
    
    SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 
    Date dateObj = curFormater.parse(dateStr); 
    SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); 
    
    String newDateStr = postFormater.format(dateObj); 
    

    【讨论】:

    • 如果谈论更改发送的数据格式 unix 时间戳是最好的选择,不是吗?
    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 2013-02-13
      • 2012-09-10
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      相关资源
      最近更新 更多