javascript 如何检查日期是否在 30 天内?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6154689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:41:35  来源:igfitidea点击:

How to check if date is within 30 days?

javascriptdate

提问by ssdesign

Possible Duplicate:
Get difference between 2 dates in javascript?

可能的重复:
在 javascript 中获取两个日期之间的差异?

I am storing date variables like this:

我正在存储这样的日期变量:

var startYear = 2011;
var startMonth = 2;
var startDay = 14;

Now I want to check if current day (today) is falling within 30 days of the start date or not. Can I do this?

现在我想检查当前日期(今天)是否在开始日期的 30 天内。我可以这样做吗?

var todayDate = new Date();
var startDate = new Date(startYear, startMonth, startDay+1);
var difference = todayDate - startDate;

????

????

I am not sure if this is syntactically or logically correct.

我不确定这在语法上或逻辑上是否正确。

回答by maerics

In JavaScript, the best way to get the timespan between two dates is to get their "time" value (number of milliseconds since the epoch) and convert that into the desired units. Here is a function to get the number of days between two dates:

在 JavaScript 中,获取两个日期之间的时间跨度的最佳方法是获取它们的“时间”值(自纪元以来的毫秒数)并将其转换为所需的单位。这是一个获取两个日期之间天数的函数:

var numDaysBetween = function(d1, d2) {
  var diff = Math.abs(d1.getTime() - d2.getTime());
  return diff / (1000 * 60 * 60 * 24);
};

var d1 = new Date(2011, 0, 1); // Jan 1, 2011
var d2 = new Date(2011, 0, 2); // Jan 2, 2011
numDaysBetween(d1, d2); // => 1
var d3 = new Date(2010, 0, 1); // Jan 1, 2010
numDaysBetween(d1, d3); // => 365

回答by Razor Storm

(todayDate.getTime() - startDate.getTime())/(1000*60*60*24.0)