在Node js中,获取时间作为输入,检查时间是否在当前时间的+3小时和-3小时范围内。我需要简单的检查而不是使用moment.js等
Input:
let time= "22 Apr 2020 06:23:55";发布于 2021-03-08 16:20:48
// create Date Object from input string:
const inputTime = new Date("22 Apr 2020 06:23:55").getTime()
// get current time
const now = Date.now()
// calculate 3 hours time span
const hhh = 60 * 60 * 3 * 1000
// calculate min && max
const min = now - hhh
const max = now + hhh
// check condition
return min < inputTime && inputTime < max发布于 2021-03-08 16:40:38
你可以使用基本的javascript Date对象。
let dateToVerify = new Date("22 Apr 2020 06:23:55").getTime()
let now = new Date.getTime()
let range = (now - dateToVerify) / (1000 * 3600)因此,如果要验证的日期是示例22 Apr 2020 06:23:55,而当前时间是Apr 22 2020 08:23:55,则范围将是2,介于您的限制之间。
getTime()以毫秒为单位。
除以(1000 * 3600)可以得到日期之间的小时数。
您还可以除以(1000 * 3600 * 24)得到一个以天为单位的范围。
然后
if (range <= 3 && range >= -3) {
// stuff
}发布于 2021-03-08 16:46:11
使用Date创建date对象,就可以像正常的毫秒数一样计算
checkDate = ( dateStr , rangeH )=>{
let timeRef = new Date(dateStr); // parse input string to date object
let now = new Date(); // get current time
let timeRange = rangeH * 60 * 60 * 1000; // calculate time range in milliseconds
return now - timeRef < timeRange && timeRef - now < timeRange
}https://stackoverflow.com/questions/66526262
复制相似问题