Aaron
Aaron

Reputation: 541

Calculating Military Time to Get Hours and Minutes Worked in Javascript

I've got a few day's worth of "clock in" and "clock out" entries in military (24 hour) time that are plain numbers.

Clock In | Clock Out
--------------------
1020     | 1555
1116     | 1857
1049     | 1204

I've manually figured out that this person has worked 14 hours and 31 minutes. I have an HTML page that contains a lot of these entries in a class, so I use the following code to get them in Javascript:

$('.clockin').each(function() {clockinsum += +$(this).text()||0;});
$('.clockout').each(function() {clockoutsum += +$(this).text()||0;});

I'm not sure where to go from here, or if this is even the right way to start. Is there a way for Javascript/jQuery to calculate the hours and minutes worked from a bunch of these entries?

Upvotes: 2

Views: 1416

Answers (2)

Koriley
Koriley

Reputation: 9

If you already have the clock in and out in an array or can put them in an array, you could just do some simple math.

var clockIn = [1555, 1857, 1204];
var clockOut = [1020, 1116, 1049];
var timeWorked = 0;
//assuming for every clock in there is a clock out
for(var i = 0; i<=clockOut.length-1; i++){

   timeWorked = timeWorked+(clockIn[i] - clockOut[i]);

}
console.log(timeWorked);

This would return 1431, which translates to 14 hours and 31 min.

Upvotes: 1

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

You need something to tell the timedifference.

In JavaScript you always work in milliseconds, so find the milliseconds difference between each start and end time, compound them and use that time to calculate time spent:

var list = [
  ["1020", "1555"],
  [1116, 1857],
  [1049, "1204"],
];
/**
 * Difference between two times in milliseconds
 *
 * @param {(number | string)} start
 * @param {(number | string)} end
 * @returns {number}
 */
function getTimeDifference(start, end) {
  var d1 = new Date(0);
  d1.setHours(parseInt(start.toString().substr(0, 2), 10));
  d1.setMinutes(parseInt(start.toString().substr(2, 2), 10));
  var d2 = new Date(0);
  d2.setHours(parseInt(end.toString().substr(0, 2), 10));
  d2.setMinutes(parseInt(end.toString().substr(2, 2), 10));
  return d2.getTime() - d1.getTime();
}
//figure how long this guy has worked:
var compiledTime = 0;
for (var index = 0; index < list.length; index++) {
  compiledTime += getTimeDifference(list[index][0], list[index][1]);
}
//At this point "compiledTime" contains the milliseconds the guy has worked
//Let's print it nice and pretty
var compiledTimeDate = new Date(compiledTime);
alert("Hours: " + compiledTimeDate.getHours() + "\n" +
  "Minutes: " + compiledTimeDate.getMinutes() + "\n" +
  "Seconds: " + compiledTimeDate.getSeconds() + "\n" +
  compiledTimeDate.getHours() + ':' + compiledTimeDate.getMinutes() + ':' + compiledTimeDate.getSeconds());
//From here you can use the Date object methods to do whatever

Upvotes: 1

Related Questions