简体   繁体   English

JavaScript检查日期是否适合最近24小时

[英]Javascript check if date fits in last 24 hours

I have a date time in javascript given in format dd.MM.yyyy HH.mm . 我在javascript中有一个日期时间,格式为dd.MM.yyyy HH.mm

What I need to check is whether this date fits in last 24 hours or not. 我需要检查的是该日期是否适合最近24小时。

Example: If date and time now is 06.04.2017 18:26 (dd.MM.yyyy HH.mm) then minimal date allowed to enter is 05.04.2017 18:26. 示例:如果现在的日期和时间是06.04.2017 18:26(dd.MM.yyyy HH.mm),则允许输入的最小日期是05.04.2017 18:26。 Is it possible to do this check with javascript? 是否可以使用javascript进行此检查?

Use the Date object to do what you want - construct a Date object for each date, then compare them using the >, <, <= or >=. 使用Date对象执行所需的操作-为每个日期构造一个Date对象,然后使用>,<,<=或> =比较它们。

Use of comparison ( ==, !=, ===, and !== ) requires you use date.getTime() as in: 使用比较(==,!=,===和!==)需要您使用date.getTime()如下所示:

 var date1 = new Date(); var date2 = new Date(date1); var same = date1.getTime() === date2.getTime(); var notSame = date1.getTime() !== date2.getTime(); console.log(same,notSame); 

 var date1 = new Date('06.04.2017 18:26'); var date2 = new Date('05.04.2017 18:26'); var isGreaterorEq = date1.getTime() >= date2.getTime(); var lessThan = date2.getTime() < date1.getTime(); console.log(isGreaterorEq ,lessThan ); 

As for the 24 hours thing: 至于24小时的事情:

 var date1 = new Date('05.06.2017 01:26'); var timeStamp = Math.round(new Date().getTime() / 1000); var timeStampYesterday = timeStamp - (24 * 3600); var is24 = date1 >= new Date(timeStampYesterday*1000).getTime(); console.log(is24,timeStamp,date1,timeStampYesterday ); 

First you have convert your date to time stamp. 首先,您已将日期转换为时间戳。 Then you have to do this calculation time stamp(now)-86400 you get the time stamp before 24hrs let us call the variable before_24 Then check your date time stamp if it is > before_24 or no. 然后,您必须执行此计算时间戳记(现在)-86400,在24小时之前获得时间戳记,让我们将变量命名为before_24,然后检查您的日期时间戳记是否大于before_24或否。

Yes you can check it with the if condition 是的,您可以使用if条件进行检查

if (parseInt(date_variable_data) > parseInt(second_date_variable_data))
{
//do action
}else
{
//do action
}

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

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