0

I'm building an app where employees can Clock in and Clock out for their shift. But I'm stuck at the time comparison part. Small explanation about the function: Users have a set shift for example from 12:00 till 15:00. They should be able to use the clock in function 2 hours prior to the start time. So from 10:00 they are able to clock in. Also these shifts are planned way ahead so we have to check for the date to be correct and the time. I've been searching for a solution but haven't found one that fits my needs.

The only data I receive through a json is the following:

date: "2016-12-07", time: "05:00"

Summary: How can I check if your current time is 2 hours before the designated time?

NOTE: It has to be a 24h clock, so no PM AM ;-)

If I have to provide more information please let me know!

ichbinblau
  • 4,507
  • 5
  • 23
  • 36
Tom Luijten
  • 185
  • 2
  • 12
  • `new Date("2016-12-07 05:00")` - will convert to js date format – ixpl0 Dec 05 '16 at 13:53
  • So do you know how to subtract dates? – epascarello Dec 05 '16 at 13:54
  • @epascarello Do you refer to something like Math.abs(date2.getTime() - date1.getTime()) to get the time differences? – Tom Luijten Dec 05 '16 at 14:01
  • @iXplo—parsing strings with the Date constructor is not a good idea. – RobG Dec 05 '16 at 20:35
  • See [*How do I get the number of days between two dates in JavaScript?*](http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript). The only difference is that you wish to resolve the time difference to hours and minutes instead of days. – RobG Dec 06 '16 at 00:32

1 Answers1

-1

You can use "momentjs", it really helps when working with dates in javascript :) For your case, take a look at moment.duration().asHours();

Their documentation says this :

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
a.diff(b, 'days', true) // 1.5

The second parameter of the function is the unit (you can type 'hours' to get it in hours). the third parameter is if yes or no it return a floating number or it round it.

Hope it may help.

Rafik Tighilt
  • 2,071
  • 1
  • 15
  • 27