Question

I apologize for the question because I have already posted a similar question, but I would like to know how I can do the following conversion:

PT11H9M38.7876754S

I want to disable seconds and only show hour and minutes 11:09

When I have time displays minutes from 1 to 9, I want to add a 0 in front of number

Tnx in advice...

Was it helpful?

Solution

You could try this:

var str = 'PT11H9M38.7876754S'
    match = str.match(/(\d*)H(\d*)M/),
    formatted = match[1] + ':' + (!match[2][1] ? 0 + match[2] : match[2]);

console.log(formatted);  // => 11:09

OTHER TIPS

"PT11H9M38.78767545".replace(/PT(\d+)H(\d+)M.*/,function(m,a,b) {return a+":"+(b.length<2?"0":"")+b;});

One-liner :p

Since all the nice RegExp stuff is above here is a third solution a bit more expensive in terms of parsing but you may be looking for something different.

You can use the split function to parse the string and extract the portions that you need.

var pt="PT11H9M38.7876754S";

function showtime(s){
    var time = s.split('.');
    var hours = time[0].split('T')[1].split('H')[0];
    var minutes = time[0].split('H')[1].split('M')[0];
    return digitize(hours) + ":" + digitize(minutes) 
}

function digitize(i){
    return (i>9) ? i : "0" + i; 
}


alert(showtime(pt)); // 11:09
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top