I want to find difference between two dates. I have tried this code but it gives me wrong values. I want get total minutes between two dates, so I am converting hours to min
You can Try This:-
function diff_hours(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60); // For Hours
//diff /= (60); For Minutes
return Math.abs(Math.round(diff));
}
dt1 = new Date(2014,10,2);
dt2 = new Date(2014,10,3);
console.log(diff_hours(dt1, dt2)); // you will get '24' hours
dt1 = new Date("October 13, 2014 08:11:00");
dt2 = new Date("October 13, 2014 11:13:00");
console.log(diff_hours(dt1, dt2)); // you will get '3' hours
Try this:
var startDate = new Date('Jan 01 2007 11:00:00');
var endDate = new Date('Jan 01 2007 11:30:00');
var starthour = parseInt(startDate.getHours());
var endhour = parseInt(endDate.getHours());
if(starthour>endhour){
alert('Hours diff:' + parseInt(starthour-endhour));
}
else{
alert('Hours diff:' + parseInt(endhour-starthour));
}
And here is the working fiddle.
var timeDiff = function (date1, date2) {
var a = new Date(date1).getTime(),
b = new Date(date2).getTime(),
diff = {};
diff.milliseconds = a > b ? a % b : b % a;
diff.seconds = diff.milliseconds / 1000;
diff.minutes = diff.seconds / 60;
diff.hours = diff.minutes / 60;
diff.days = diff.hours / 24;
diff.weeks = diff.days / 7;
return diff;
}
Try this code (uses ms as initial units)
var timeStart = new Date("Mon Jan 01 2007 11:00:00 GMT+0530").getTime();
var timeEnd = new Date("Mon Jan 01 2007 11:30:00 GMT+0530").getTime();
var hourDiff = timeEnd - timeStart; //in ms
var secDiff = hourDiff / 1000; //in s
var minDiff = hourDiff / 60 / 1000; //in minutes
var hDiff = hourDiff / 3600 / 1000; //in hours
var humanReadable = {};
humanReadable.hours = Math.floor(hDiff);
humanReadable.minutes = minDiff - 60 * humanReadable.hours;
console.log(humanReadable); //{hours: 0, minutes: 30}
JSFiddle: http://jsfiddle.net/n2WgW/
Try:
var diffHrs = Math.floor((hourDiff % 86400000) / 3600000);
Math.round
rounded the 0.5
hour difference up to 1
. You only want to get the "full" hours in your hours variable, do you remove all the minutes from the variable with the Math.floor()
You can get Time Difference in hours and minutes format like below
const startTime = new Date(event.startTime);
const endTime = new Date(event.endTime);
const diff = endTime.getTime() - startTime.getTime();
const hrDiff = diff / 3600 / 1000; // 1.555555
const totalHours = parseFloat((hrDiff).toFixed(2)); // 1.5