如何检查日期是否在30天内? [英] How to check if date is within 30 days?

查看:94
本文介绍了如何检查日期是否在30天内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在javascript中两个日期之间有区别吗?

我存储这样的日期变量:

I am storing date variables like this:

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

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

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

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.

推荐答案

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

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:

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

这篇关于如何检查日期是否在30天内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆