如何将时间跨度字符串解析为小时,分钟? [英] How can I parse timespan string to hour, minutes?

查看:129
本文介绍了如何将时间跨度字符串解析为小时,分钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串"P18DT5H2M3S",表示:18天5小时2分钟3秒.

I have a string "P18DT5H2M3S" which means: 18 days, 5 hours, 2 minutes, 3 seconds.

我必须将此字符串解析为小时和分钟.我应该使用正则表达式还是split或substr等...

I have to parse this string to hour and minute. Should I use regex or split or substr etc...?

(关于此推荐答案

所以我接受了@ chandil03的答案,并对其进行了调整,以返回HH:MM:SS格式.

So I took @chandil03's answer and tweaked it to return a HH:MM:SS format.

 var stamp = "PT2H10M13S"

    // strip away the PT

    stamp = stamp.split("PT")[1];

    // split at every character

    var tokens = stamp.split(/[A-Z]+/);

    // If there are any parts of the time missing fill in with an empty string.
    // e.g "13S" we want ["", "", "13", ""]

    for(var i = 0; i < 4 - stamp.length; i++){
       tokens.unshift("");
    }

    // Here we add logic to pad the values that need a 0 prepended.

    var stampFinal = tokens.map(function(t){
        if(t.length < 2){
            if(!isNaN(Number(t))){
               return ("0"  + Number(t).toString());
            }
         }
         return t;
    });

    // pop the last element because it is an extra. 

    stampFinal.pop();

    console.log(stampFinal.join(":"));

这篇关于如何将时间跨度字符串解析为小时,分钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆