javascript - 检查日期字符串是否大于 3 天

标签 javascript

我需要一些关于 javascript 代码的帮助,如果第二个日期大于 3 天,我需要检查两个字符串日期值(第一个日期和第二个日期),我得到字符串格式的值 mm/dd/yyyy。请帮忙。

var firstDate = '10/01/2019'
var secondDate = '10/04/2019'

if ((inputData.firstDate) + 3 === inputData.secondDate) {
  return {
    dateCheck: 'Not greater than 3 days'
  };
} else {
  return {
    dateCheck: 'Greater than 3 days'
  };
}

最佳答案

要将 N 天添加到您使用的日期 Date.getDate() + N

var d1 = new Date('10/01/2019');
var d2 = new Date('10/04/2019');
var isGreater = +d2 > d1.setDate(d1.getDate() + 3); // false (equals three days)

鉴于以上内容,您可以制作一个简单的可重用函数

/**
 * Check if d2 is greater than d1
 * @param {String|Object} d1 Datestring or Date object
 * @param {String|Object} d2 Datestring or Date object
 * @param {Number} days Optional number of days to add to d1
 */
function isDateGreater (d1, d2, days) {
  d1 = new Date(d1);
  return +new Date(d2) > d1.setDate(d1.getDate() + (days||0))
}

console.log(isDateGreater('10/01/2019', '10/03/2019', 3)); // false (smaller)
console.log(isDateGreater('10/01/2019', '10/04/2019', 3)); // false (equal)
console.log(isDateGreater('10/01/2019', '10/05/2019', 3)); // true (greater than)
// Without the optional third parameter
console.log(isDateGreater('10/01/2019', '10/05/2019')); // true (is greater date)

回顾一下:创建一个函数,在将日期添加 N 天后,计算两个时间戳。

Date.setDate MDN
Date.getDate MDN

关于javascript - 检查日期字符串是否大于 3 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54383799/

相关文章:

javascript - 如何使用 firebase auth 实现重新发送 OTP

javascript - 任何人都可以在云中成功部署 GAE Spring BOOT 应用程序吗

javascript - Sweetalert2 在表单内无法正常工作

javascript - knockout validation : how to validate the fields on button click, 不在输入更改时

javascript - 编程新手,试图解决这个 Isogram kata(使用 .match javascript)

javascript - 使用 Javascript 生成动态数据

javascript - 如何创建类似 Chrome 手机的菜单动画?

JavaScript Express、 Node 和 CSVtoJSON

javascript - ng-click 事件 AngularJS 的捕获时间 - 这可能吗?

javascript - 我正在创建一个带有 react-native-elements 的复选框列表。我如何一次只选中一个框?