首页 > 解决方案 > 如何为现在日期和预定义日期设置相等条件?

问题描述

我正在尝试设置下面的条件来运行 Condition1 if new Date(visitationDate)is equal to Date.now()

在前端,visitationDate 进来,Thu Nov 11 2021 13:52:33 GMT+0100 (West Africa Standard Time)我用函数将其转换为格式2021-11-11T13:00:00.000Z,然后将其发送到后端。我在后端的问题中使用日期条件。如果它可以解决我的问题,我可以在前端恢复转换。

这是我当前在后端使用的代码

if (new Date(visitationDate) == Date.now()) {
   Condition1
} else {
   Condition2
}

我的问题是如果visitationDate 小于Date.now() 或Date.now() 大于visitationDate,我该如何运行Condition2。仅当 visitationDate 是当前日期或等于 24 小时窗口中的 Date.now() 时,我才想运行 Condition1。

标签: javascriptdate

解决方案


似乎您想比较没有时间部分的日期,因此将输入时间戳转换为日期并将其与当前本地日期进行比较,例如

// Convert standard toString format to YYYY-MM-DD without changing the date
function reformatDate(s) {
  // Parse string as UTC+0  
  let d = new Date(s.replace(/GMT\+.*/,'GMT+0000'));
  // Return date only in ISO 8601 format
  return d.toISOString().substring(0,10);
}

// Return date as local YYYY-MM-DD
function formatDate(d) {
  return d.toLocaleDateString('en-CA');
}

let ts = 'Thu Nov 11 2021 13:52:33 GMT+0100 (West Africa Standard Time)';
// Date with some random time
let d = new Date(2021,10,11,23,59,59);
console.log(formatDate(d) + ' : ' +  (reformatDate(ts) == formatDate(d)));

// Compare to today
d = new Date();
console.log(formatDate(d) + ' : ' +  (reformatDate(ts) == formatDate(d)));


推荐阅读