vardha - 1 year ago 67
Javascript Question

# Time difference between 2 datetime moment

SO i have 2 datetime objects .

now = Nov 15 4:00 PM
later = Nov 15 6:00PM

My objective is to get the total hours between (9AM to 5 PM) , given the now and later times.

resulting answer shud be 1 hour. (since im only concerned about time range that falls within 9AM-5PM)

now = Nov 15 6:00 AM
later = Nov 15 8:00 PM

resulting answer should be 8 hours.

is the best way to achieve this using the diff function in moment and stripping the hour out and calculating individual use cases ( when start time less than 9AM/ start time greater than 9AM) . similarly end time (less than 5PM/greater than 5PM) etc?

Also how to tackle this case where,

now = Nov 15 9:00AM
later = Nov 18 2:00PM

8(nov 15)+8(nov 16)+8(nov 17)+5(nov 18) = 29hrs

Here's working solution

var now = moment("15 Nov 2016, 9:00:00 am", "DD MMM yyyy, h:mm:ss a").toDate();
var later = moment("18 Nov 2016, 2:00:00 pm", "DD MMM yyyy, h:mm:ss a").toDate();

function getWorkingHours(now, later) {
var hoursToday = 0;

var workingHourStart = 9;
var workingHourEnd = 17;//5pm
var workDuration = workingHourEnd - workingHourStart;

if(workingHourEnd - getHours(now) > 0) {
hoursToday = (workingHourEnd - getHours(now));
hoursToday = (hoursToday > workDuration) ? workDuration : hoursToday;
}

var hoursLater = 0;

if(getHours(later) - workingHourStart > 0) {
hoursLater = (getHours(later) - workingHourStart);
hoursLater = (hoursLater > workDuration) ? workDuration : hoursLater;
}

var actualDiffHours = (later.getTime() - now.getTime()) / (1000 * 60 * 60);
var actualHoursInBetween = actualDiffHours - (24 - getHours(now)) - getHours(later);

var workingHoursInBetween = (actualHoursInBetween / 24) * 8;

return hoursToday + workingHoursInBetween + hoursLater;
}

function getHours(date) {
var hours = date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600 + date.getMilliseconds() / 3600/1000;
return hours;
}

console.log(getWorkingHours(now, later));