How can I convert time to decimal number in JavaScript?

淺唱寂寞╮ 提交于 2019-12-04 04:40:59

Separate hours and minutes, divide minutes by 60, add to hours.

function timeStringToFloat(time) {
  var hoursMinutes = time.split(/[.:]/);
  var hours = parseInt(hoursMinutes[0], 10);
  var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
  return hours + minutes / 60;
}

In my case I use it for calculating time on invoice.

The input could contain these 6 ways to write it for the user :

  • 1 -> 1 hour 0 minutes
  • 1,2 -> 1 hour 12 minutes
  • 1.5 -> 1 hour 30 minutes
  • 1:30 -> 1 hour 30 minutes
  • 1h40 -> 1 hour 40 minutes
  • 45m -> 0 hour 45 minutes

So I used this (thanks to Amadan), here is working code :

function time2dec(tIn) {
    if(tIn == '') 
        return 0;
    if(tIn.indexOf('h') >= 0 || tIn.indexOf(':') >= 0)
        return hm2dec(tIn.split(/[h:]/));
    if(tIn.indexOf('m') >= 0)
        return hm2dec([0,tIn.replace('m','')]);
    if(tIn.indexOf(',') >= 0)
        return parseFloat(tIn.split(',').join('.')).toFixed(2);
    if(tIn.indexOf('.') >= 0)
        return parseFloat(tIn);
    return parseInt(tIn, 10);
}

function hm2dec(hoursMinutes) {
    var hours = parseInt(hoursMinutes[0], 10);
    var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
    return (hours + minutes / 60).toFixed(2);
}

Example of use (with jQuery) :

var qty = time2dec($('#qty').val());
var price = parseFloat($('#price').val());
var total = (qty * price).toFixed(2);

Hope it could help some of us.

Svetoslav

Another way ;)

var aHours = 4.45;

var aHoursInMinutes = (Math.floor(aHours) * 60 )+ ((aHours - Math.floor(aHours)) * 100);
 // 285 minutes;

var afromMinutesToHours = 
(Math.floor(aHoursInMinutes /60) + ((aHoursInMinutes - (60* Math.floor(aHoursInMinutes /60)))/100));
 // 4.45 hours;

var bHours = 0.33;

var bHoursInMinutes = (Math.floor(bHours) * 60 )+ ((bHours - Math.floor(bHours)) * 100); // 33 minutes;

var bFromMinutesToHours = 
(Math.floor(bHoursInMinutes / 60) + (( bHoursInMinutes - (60 * Math.floor(bHoursInMinutes / 60)))/100)); // 0.33 hours;

var resultInMinutes = aHoursInMinutes + bHoursInMinutes;
var resultToHours = 
(Math.floor(resultInMinutes / 60) + (( resultInMinutes - (60 * Math.floor(resultInMinutes  / 60)))/100)); // 5.18 hours;

As alternative, I was curious if this could be done using Date.parse, and it can.

The following code returns the same values as the selected answer, except for garbage input in which case it returns zero. The 1970 date is used because that is UNIX time zero.

Note that MDN says, "It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent."

var test = [undefined, null, "", "garbage", "0", "00:00", "  01:11", "3:44", "2:3", "5.06"];
var hours = 0;
var html = "<table>";

for (var i = 0; i < test.length; i++) {
  html += "<tr>";
  html += "<td>" + test[i] + "</td>";
  hours = timeStringToFloat(test[i]);
  html += "<td>" + hours + "</td>";
  hours = timeStringToNumber(test[i]);
  html += "<td>" + hours + "</td>";
  html += "<td>" + hoursToString(hours) + "</td>";
  html += "</tr>";
}
stdout.innerHTML = html;

function timeStringToNumber(time) {
  return ((new Date(("01 Jan 1970 " + time || "").replace(".", ":") + " GMT")) / 3600000) || 0;
}

function timeStringToFloat(time) {
  try {
    var hoursMinutes = time.split(/[.:]/);
    var hours = parseInt(hoursMinutes[0], 10);
    var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
    return hours + minutes / 60;
  } catch (e) {
    return "ERROR";
  }
}

function hoursToString(hours) {
  var minutes = hours * 60;
  return (
    ("00" + Math.floor(minutes / 60)).slice(-2) +
    ":" +
    ("00" + Math.round(minutes % 60)).slice(-2)
  );
}
body {
  font-family: sans-serif;
  font-size: 12px;
}

h4 {
  color: white;
  background-color: steelblue;
  padding: 0.5em;
}

table {
  border-collapse: collapse;
}

table td {
  border: 1px solid gray;
  min-height: 1em;
}
<h4>Test Output:</h4>
Method A is the original and Method B the alternative.
<table>
  <thead>
    <tr>
      <th>String</th>
      <th>Method A</th>
      <th>Method B</th>
      <th>ToString</th>
    </tr>
  </thead>
  <tbody id="stdout"></tbody>
</table>

*

function timeStringToNumber( time ) 
{
    return ((new Date(("01 Jan 1970 " + time || "").replace(".",":") + " GMT")) / 3600000) || 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!