有人能提出一种方法来比较两个大于、小于和过去不使用JavaScript的日期的值吗?值将来自文本框。
当前回答
嗨,这是我比较日期的代码。在我的情况下,我正在检查是否允许选择过去的日期。
var myPickupDate = <pick up date> ;
var isPastPickupDateSelected = false;
var currentDate = new Date();
if(currentDate.getFullYear() <= myPickupDate.getFullYear()){
if(currentDate.getMonth()+1 <= myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
if(currentDate.getDate() <= myPickupDate.getDate() || currentDate.getMonth()+1 < myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
isPastPickupDateSelected = false;
return;
}
}
}
console.log("cannot select past pickup date");
isPastPickupDateSelected = true;
其他回答
注意-仅比较日期部分:
当我们在javascript中比较两个日期时。这需要数小时、数分钟和数秒的时间。。因此,如果我们只需要比较日期,这是一种方法:
var date1= new Date("01/01/2014").setHours(0,0,0,0);
var date2= new Date("01/01/2014").setHours(0,0,0,0);
现在:如果date1.valueOf()>date2.valueOf。
为了从JavaScript中的自由文本创建日期,您需要将其解析为Date对象。
您可以使用Date.parse(),它获取自由文本并尝试将其转换为新的日期,但如果您能够控制页面,我建议使用HTML选择框或日期选择器,例如YUI日历控件或jQueryUI日期选择器。
正如其他人所指出的,一旦你有了日期,你就可以使用简单的算术来减去日期,并将其转换为天数,方法是将数字(以秒为单位)除以一天中的秒数(60*60*24=86400)。
为了在众多现有选项中添加另一种可能性,您可以尝试:
if (date1.valueOf()==date2.valueOf()) .....
…这似乎对我有用。当然,你必须确保这两个日期都没有定义。。。
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....
通过这种方式,我们可以确保如果两者都未定义,或者。。。
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....
…如果你希望他们不平等。
关系运算符<<=>>=可用于比较JavaScript日期:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 2);
d1 < d2; // true
d1 <= d2; // true
d1 > d2; // false
d1 >= d2; // false
然而,等式运算符==!===!==无法用于比较(的值)日期,因为:
对于严格或抽象的比较,两个不同的对象永远不相等。只有当操作数引用同一对象时,比较对象的表达式才为真。
您可以使用以下任一方法比较相等的日期值:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 1);
/*
* note: d1 == d2 returns false as described above
*/
d1.getTime() == d2.getTime(); // true
d1.valueOf() == d2.valueOf(); // true
Number(d1) == Number(d2); // true
+d1 == +d2; // true
Date.getTime()和Date.valueOf()都返回自1970年1月1日00:00UTC以来的毫秒数。Number函数和一元+运算符都在幕后调用valueOf()方法。
“一些”发布的代码的改进版本
/* Compare the current date against another date.
*
* @param b {Date} the other date
* @returns -1 : if this < b
* 0 : if this === b
* 1 : if this > b
* NaN : if a or b is an illegal date
*/
Date.prototype.compare = function(b) {
if (b.constructor !== Date) {
throw "invalid_date";
}
return (isFinite(this.valueOf()) && isFinite(b.valueOf()) ?
(this>b)-(this<b) : NaN
);
};
用法:
var a = new Date(2011, 1-1, 1);
var b = new Date(2011, 1-1, 1);
var c = new Date(2011, 1-1, 31);
var d = new Date(2011, 1-1, 31);
assertEquals( 0, a.compare(b));
assertEquals( 0, b.compare(a));
assertEquals(-1, a.compare(c));
assertEquals( 1, c.compare(a));