简体   繁体   English

具有时差的日期比较(JS)

[英]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. 关于此功能的简短说明:例如,用户在12:00至15:00之间有一个设定的班次。 They should be able to use the clock in function 2 hours prior to the start time. 他们应该能够在开始时间之前2小时使用时钟功能。 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. 因此,他们可以从10:00开始计时。此外,这些班次都计划提前进行,因此我们必须检查日期和时间是否正确。 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: 我通过json接收的唯一数据如下:

date: "2016-12-07", time: "05:00" 日期:“ 2016-12-07”,时间:“ 05:00”

Summary: How can I check if your current time is 2 hours before the designated time? 摘要:如何检查您的当前时间是否比指定时间早2小时?

NOTE: It has to be a 24h clock, so no PM AM ;-) 注意:它必须是24小时制,所以没有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(); 您可以使用“ momentjs” ,它在使用javascript中的日期时确实有帮助:)对于您的情况,请查看一下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). 函数的第二个参数是单位(您可以键入“ hours”以小时为单位)。 the third parameter is if yes or no it return a floating number or it round it. 第三个参数是“是”或“否”,则返回一个浮点数或四舍五入。

Hope it may help. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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