How Can I Parse Timespan String To Hour, Minutes?
I have a string 'P18DT5H2M3S' which means: 18 days, 5 hours, 2 minutes, 3 seconds. I have to parse this string to hour and minute. Should I use regex or split or substr etc...? (re
Solution 1:
You can use whatever you want.
Following is the example using split method with regex.
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]);
You can do with substr but for this you have to find index of letters. So Spit with regex is simpler approach.
Solution 2:
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 charactervar 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(":"));
Solution 3:
I found this page: http://www.petershev.com/blog/net-timespans-returned-by-breeze-js-or-working-with-iso8601-duration-standard/
So when I added to https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js this js,
I can convert duration = moment.duration.fromIsoduration('P18DT5H2M3S'); duration._data can be used it has _days, _hours, _minutes
Solution 4:
Please, find my solution based on inoabrian's.
functionfromString(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];
}
Post a Comment for "How Can I Parse Timespan String To Hour, Minutes?"