简体   繁体   中英

Date comparison with hour differences (JS)

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM