用JavaScript比较两个日期
有人可以提出一种方法来比较两个日期的值大于,小于,而不是过去使用JavaScript? 这些值将来自文本框...
Date对象会做你想做的 - 为每个日期构造一个,然后使用>
, <
, <=
或>=
来比较它们。
==
, !=
, ===
和!==
运算符要求您使用date.getTime()
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
要明确直接检查与数据对象的相等性是行不通的
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
尽管如此,我建议你使用下拉式或类似约束形式的日期输入而不是文本框,以免发现自己处于输入验证地狱。
在javascript中比较日期的最简单方法是首先将其转换为Date对象,然后比较这些日期对象。
在下面你会发现一个有三个功能的对象:
dates.compare(A,B)
返回一个数字:
dates.inRange (d,开始,结束)
返回一个布尔值或NaN:
dates.convert
由其他函数用于将其输入转换为日期对象。 输入可以是
。
// Source: http://stackoverflow.com/questions/497790
var dates = {
convert:function(d) {
// Converts the date in d to a date-object. The input can be:
// a date object: returned without modification
// an array : Interpreted as [year,month,day]. NOTE: month is 0-11.
// a number : Interpreted as number of milliseconds
// since 1 Jan 1970 (a timestamp)
// a string : Any format supported by the javascript engine, like
// "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
// an object : Interpreted as an object with year, month and date
// attributes. **NOTE** month is 0-11.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
// Compare two dates (could be of any type supported by the convert
// function above) and returns:
// -1 : if a < b
// 0 : if a = b
// 1 : if a > b
// NaN : if a or b is an illegal date
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
// Checks if date in d is between dates in start and end.
// Returns a boolean or NaN:
// true : if d is between start and end (inclusive)
// false : if d is before start or after end
// NaN : if one or more of the dates is illegal.
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
像往常一样比较<
和>
,但涉及=
任何内容都应使用+
前缀。 像这样:
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
// less than, greater than is fine:
x < y; => false
x > y; => false
x === y; => false, oops!
// anything involving '=' should use the '+' prefix
// it will then compare the dates' millisecond values
+x <= +y; => true
+x >= +y; => true
+x === +y; => true
希望这可以帮助!
链接地址: http://www.djcxy.com/p/3115.html