如何检查两个日期之间的时间是否超过一定的月数?

How do I check if the time between two dates exceeds a certain number of months?

我有一个应用程序,用户可以在其中 select 两个日期(开始日期和结束日期)并且日期之间的时间不应超过 4 个月。用户可以 select 每个日期的日、月和年。我可以使用某种逻辑来实现这一点,以便在日期范围超过 4 个月时返回错误。每个输入都是一个整数。例如,2019 年 3 月 31 日的开始日期为:from_date_day = 31 from_date_month = 3from_date_year = 2019

例如,我喜欢这样的工作:

((Math.abs($('#to_date_month').val() - $('#from_date_month').val()) > 2) && $('#from_date_day').val() <= $('#to_date_day').val()
  return "error"

此代码的问题是当日期跨越两个不同的年份时它不起作用。我正在使用 coffeescript,但 jquery 或 js 中的解决方案也可以。

我建议为这两个日期创建两个 Javascript Date 对象。这可以通过将年、月和最后的日提供给 Date 对象的构造函数来完成。

例如

var startDate = new Date(2019, 1, 16); // January the 16th
var endDate = new Date(2019, 3, 30); // March the 30th

使用 Date 对象的 .getTime() 函数,您可以获得自 1.1.1970 以来经过的毫秒数。如果您计算这两个数字之间的差值,将其包裹在 Math.abs() 中,然后将该数字除以 10006060,最后得到 24天数。如果这个数字大于~120,则范围大于四个月。

console.log(Math.abs(startDate.getTime() - endDate.getTime()) / 1000/60/60/24);

在您的用例中,日期对象可以这样设置:

var startDate = new Date(parseInt($('#from_date_year').val()), parseInt($('#from_date_month').val()), parseInt($('#from_date_day').val()));