Sumit Pathak
Sumit Pathak

Reputation: 661

Convert integers to time and add

I have requirement to converting integer value to time format using javascript.

My requirement is that the result should be in time format.

Example 08:55 and 09:55

If I add these two as numbers then I will get 18.10 but I need 18:50

Upvotes: 0

Views: 206

Answers (1)

Mr_Green
Mr_Green

Reputation: 41842

Try this: (My solution assumes the sum of times is not more than 24 hours)

function pad(str) { 
    return ("00"+str).slice(-2);
} 
var str1 = "08:55";
var str2 = "09:55";
var token1 = str1.split(":");
var token2 = str2.split(":");
var result = token1[0] * 60 + + token1[1] + + token2[0] * 60 + + token2[1];
var newTime = pad(Math.floor(result/60)) + ":" + pad(result % 60);
console.log(newTime);

Upvotes: 2

Related Questions