Reputation: 5411
I'm using a date.js
plugin to convert my times into date object and then I'm subtracting them.But the result is not valid. My time is in this format 11:00 pm
This is what I'm doing:
var tim_i = $('#in_time').val();
var tim_o = $('#out_time').val();
total_tim = "";
if (tim_i && tim_o ){
d1 = Date.parse(tim_i);
d2 = Date.parse(tim_o);
date_diff = new Date(d2 - d1);
total_tim=date_diff.getHours() + ':' + date_diff.getMinutes();
}
$('#total_time').val(total_tim);
Is there something else I need to do?
Upvotes: 0
Views: 4134
Reputation: 2385
The TimeSpan class in Datejs might help simplify the problem.
Here's a sample you can run in Firebug that parse the two strings into Date objects, then output the difference in Hours + Minutes.
Example
var d1 = Date.parse("6:30 am");
var d2 = Date.parse("11:00 pm");
var diff = new TimeSpan(d2 - d1);
console.log("Hours: ", diff.hours);
console.log("Minutes: ", diff.minutes);
Hope this helps.
EDIT: You could even simplify into one line if you really want to be terse.
new TimeSpan(Date.parse("11:00 pm")-Date.parse("6:30 am")).toString("H:mm")
Upvotes: 1
Reputation: 73916
Try this:
var tim_i = new Date($('#in_time').val());
var tim_o = new Date($('#out_time').val());
total_tim = "";
if (tim_i && tim_o) {
var timeDiff = Math.abs(tim_o.getTime() - tim_i.getTime());
var getHours = Math.ceil(timeDiff / (1000 * 3600));
var getMinutes = Math.ceil(timeDiff % (1000 * 60));
total_tim = getHours + ':' + getMinutes;
}
Upvotes: 0