简体   繁体   中英

Javascript convert HH:MM to decimal

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.

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

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'));

You shouldn't put an = after the return, and let the Math generate the decimal point for you.

This should do it

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

console.log(timeToDecimal('04:30')); // 4.5
console.log(timeToDecimal('04:22')); // 4.366666666666666
console.log(timeToDecimal('12:05')); // 12.083333333333334

Depending on what kind of calculations you want to do, you might want to round the result of course.

Here's the Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM