Reputation: 9905
In JavaScript, jQuery, moment.js or any library,
how would u change a numeric value like 116265 (11 hours, 62 minutes, 65 seconds)
into the correct time value 12:03:05 ?
Edit/Update:
It must work also if the hours are bigger then 2 digits. (In my case the hours are the only part that can be bigger then 2 digits.)
Upvotes: 1
Views: 287
Reputation: 2412
Try this
var a = '116265'.replace(/^(\d+)(\d{2})(\d{2})$/, '$1:$2:$3')
var hms = a; // your input string
var a = hms.split(':'); // split it at the colons
if (a[2] >= 60) {
a[2] -= 60, a[1] ++;
}
if (a[1] >= 60) {
a[1] -= 60, a[0] ++;
}
console.log(a[0] + ":" + ("0" + a[1]).slice(-2) + ":" + ("0" + a[2]).slice(-2));
Upvotes: 1
Reputation: 115222
Use replace()
method with function
console.log(
'116265'.replace(/^(\d+)(\d{2})(\d{2})$/, function(m, m1, m2, m3) {
m1 = Number(m1); // convert captured group value to number
m2 = Number(m2);
m2 = Number(m2);
m2 += parseInt(m3 / 60, 10); // get minutes from second and add it to minute
m3 = m3 % 60; // get soconds
m1 += parseInt(m2 / 60, 10); // get minutes from minute and add it to hour
m2 = m2 % 60; // get minutes
// add 0 to minute and second if single digit , slice(-2) will select last 2 digit
return m1 + ':' + ('0' + m2).slice(-2) + ':' + ('0' + m3).slice(-2); // return updated string
})
)
Upvotes: 4