【问题标题】:How can I parse timespan string to hour, minutes?如何将时间跨度字符串解析为小时、分钟?
【发布时间】:2015-11-09 18:25:46
【问题描述】:
【问题讨论】:
标签:
javascript
regex
parsing
timespan
【解决方案1】:
请根据inoabrian 的方法找到我的解决方案。
function fromString(timeSpan) {
var hours = 0;
var minutes = 0;
var seconds = 0;
if (timeSpan != null && typeof (timeSpan) == 'string' && timeSpan.indexOf('PT') > -1) {
timeSpan = timeSpan.split("PT")[1].toLowerCase();
var hourIndex = timeSpan.indexOf('h');
if (hourIndex > -1)
{
hours = parseInt(timeSpan.slice(0, hourIndex));
timeSpan = timeSpan.substring(hourIndex + 1);
}
var minuteIndex = timeSpan.indexOf('m');
if (minuteIndex > -1)
{
minutes = parseInt(timeSpan.slice(0, minuteIndex));
timeSpan = timeSpan.substring(minuteIndex + 1);
}
var secondIndex = timeSpan.indexOf('s');
if (secondIndex > -1)
seconds = parseInt(timeSpan.slice(0, secondIndex));
}
return [hours, minutes, seconds];
}
【解决方案2】:
所以我接受了@chandil03 的回答并对其进行了调整以返回 HH:MM:SS 格式。
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(":"));
【解决方案4】:
你可以使用任何你想要的东西。
以下是使用正则表达式拆分方法的示例。
var res = "P18DT5H2M3S";
var tokens = res.split(/[A-Z]+/);
//var str = "D:"+token[1]+" H:"+tokens[2]+" M:"+tokens[3]+" S:"+tokens[4];
alert("D:"+tokens[1]+" H:"+tokens[2]+" M:"+tokens[3]+" S:"+tokens[4]);
你可以用 substr 来做,但为此你必须找到字母索引。所以 Spit with regex 是更简单的方法。