Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript convert HH:MM to decimal

Tags:

javascript

I have a Javascript function that gives me the total hours worked in a day as HH:MM. I want to convert those numbers to decimals so I can add them up. I just seem to be getting errors at the moment:

function timeToDecimal(t) {
t = t.split(':');
return = t[0]*1 + '.' parseInt(t[1])/60;
}    

Am I missing something important? I just keep getting syntax errors.

like image 933
Jason B Avatar asked Apr 02 '14 18:04

Jason B


Video Answer


2 Answers

function timeToDecimal(t) {
    var arr = t.split(':');
    var dec = parseInt((arr[1]/6)*10, 10);

    return parseFloat(parseInt(arr[0], 10) + '.' + (dec<10?'0':'') + dec);
}   

FIDDLE

returns a number with two decimals at the most

timeToDecimal('00:01') // 0.01
timeToDecimal('00:03') // 0.05
timeToDecimal('00:30') // 0.5
timeToDecimal('10:10') // 10.16
timeToDecimal('01:30') // 1.5
timeToDecimal('3:22' ) // 3.36
timeToDecimal('22:45') // 22.75
timeToDecimal('02:00') // 2
like image 75
adeneo Avatar answered Sep 28 '22 22:09

adeneo


Some minor syntax errors as stated above:

Remove the '=', '.' and add parseInt

function timeToDecimal(t) {
  t = t.split(':');
  return parseInt(t[0], 10)*1 + parseInt(t[1], 10)/60;
}  

For the sake of completeness, here's a functional solution that would allow you to add more levels of accuracy: jsfiddle

function timeToDecimal(t) {
  return t.split(':')
          .map(function(val) { return parseInt(val, 10); } )
          .reduce( function(previousValue, currentValue, index, array){
              return previousValue + currentValue / Math.pow(60, index);
          });
};

console.log(timeToDecimal('2:49:50'));
like image 40
Pete Avatar answered Sep 28 '22 22:09

Pete