Javascript将HH:MM转换为十进制

时间:2014-04-02 18:45:36

标签: javascript

我有一个Javascript函数,它给我一天工作的总时数为HH:MM。我想将这些数字转换为小数,以便我可以添加它们。我此刻似乎遇到了错误:

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

我错过了重要的事情吗?我只是不断收到语法错误。

3 个答案:

答案 0 :(得分:12)

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

返回最多两位小数的数字

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

答案 1 :(得分:1)

如上所述的一些小的语法错误:

删除'=','。'并添加parseInt

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

为了完整起见,这是一个功能性解决方案,可以让您添加更多级别的准确度: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'));

答案 2 :(得分:0)

您不应该在返回后放置=,让Math为您生成小数点。

这应该这样做

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

根据您想要进行的计算类型,您可能希望对结果进行舍入。

这是Fiddle