javascript - 如何为现在日期和预定义日期设置相等条件?
问题描述
我正在尝试设置下面的条件来运行 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。
解决方案
似乎您想比较没有时间部分的日期,因此将输入时间戳转换为日期并将其与当前本地日期进行比较,例如
// 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)));
推荐阅读
- azure-iot-hub - HttpExtensionErrorResponse-“消息”:“图像必须为 416x416” - Yolov3 边缘模块
- oauth-2.0 - 使用 Apple 调试 Sign(无效的 Web 重定向 url)
- javascript - 十六进制到二进制和二进制操作的麻烦
- java - 在spring boot中使用post方法时无法返回html
- reactjs - 无法通过反应本机导航导航到有条件地设置屏幕
- windows - 将 Windows 2016 DC 服务器就地升级到 2019 失败
- docker - ddev:“无法运行 docker-compose ...”错误
- shell - 如何通过 shell 删除每个 dn 会话中的重复条目
- javascript - 如何将mysql结果写入变量?
- r - 如何对一列值求和并按另一列的间隔对它们进行分组