Cris Cris - 6 months ago 17
jQuery Question

datejavascript change a numeric value into time value

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.)

Answer

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
  })
)

Comments