Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert time to decimal number in JavaScript?

I'm too lazy to fill out my time sheet at work by the end at the end of every month, so I've started adding some functions to our PDF form. Acrobat Pro offers to make advanced calculations using JavaScript, but I'm stuck with this problem.

I have two fields in which I enter the time when I start/end working. I want to calculate my overtime and output the result in a third field. however, I want the output to be decimal, so when I make half an hour overtime, the result would be 0.5

Example: my work time is 8.5 hours, I start a 7.30 and finish at 16.00 (4 pm).

My code so far:

var workTime = this.getField("Work time").value;
var startTime = this.getField("Start time").value;
var endTime = this.getField("End time").value;

event.value = workTime - (endTime - startTime);
like image 955
idleberg Avatar asked Jun 05 '12 07:06

idleberg


2 Answers

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;
}
like image 137
Amadan Avatar answered Sep 21 '22 06:09

Amadan


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.

like image 29
Meloman Avatar answered Sep 19 '22 06:09

Meloman