有人能提出一种方法来比较两个大于、小于和过去不使用JavaScript的日期的值吗?值将来自文本框。
当前回答
假设您处理的是2014年[:-/.]06[:-//.]06或2014年06月[:-/./.]06日格式,那么您可以这样比较日期
var a = '2014.06/07', b = '2014-06.07', c = '07-06/2014', d = '07/06.2014';
parseInt(a.replace(/[:\s\/\.-]/g, '')) == parseInt(b.replace(/[:\s\/\.-]/g, '')); // true
parseInt(c.replace(/[:\s\/\.-]/g, '')) == parseInt(d.replace(/[:\s\/\.-]/g, '')); // true
parseInt(a.replace(/[:\s\/\.-]/g, '')) < parseInt(b.replace(/[:\s\/\.-]/g, '')); // false
parseInt(c.replace(/[:\s\/\.-]/g, '')) > parseInt(d.replace(/[:\s\/\.-]/g, '')); // false
如您所见,我们去掉分隔符,然后比较整数。
其他回答
function datesEqual(a, b)
{
return (!(a>b || b>a))
}
为了从JavaScript中的自由文本创建日期,您需要将其解析为Date对象。
您可以使用Date.parse(),它获取自由文本并尝试将其转换为新的日期,但如果您能够控制页面,我建议使用HTML选择框或日期选择器,例如YUI日历控件或jQueryUI日期选择器。
正如其他人所指出的,一旦你有了日期,你就可以使用简单的算术来减去日期,并将其转换为天数,方法是将数字(以秒为单位)除以一天中的秒数(60*60*24=86400)。
使用momentjs进行日期操作。
使用
isSameOrAfter()方法
moment('2010-10-20').isSameOrAfter('2010-10-20') //true;
使用isAfter()方法检查一个日期是否在另一个日期之后
moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true
使用isBefore()方法检查一个日期是否早于另一个日期。
moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false
使用isSame()方法检查一个日期与另一个日期是否相同
moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true
from_date ='10-07-2012';
to_date = '05-05-2012';
var fromdate = from_date.split('-');
from_date = new Date();
from_date.setFullYear(fromdate[2],fromdate[1]-1,fromdate[0]);
var todate = to_date.split('-');
to_date = new Date();
to_date.setFullYear(todate[2],todate[1]-1,todate[0]);
if (from_date > to_date )
{
alert("Invalid Date Range!\nStart Date cannot be after End Date!")
return false;
}
使用此代码使用javascript比较日期。
谢谢D.吉普
尝试使用此代码
var f =date1.split("/");
var t =date2.split("/");
var x =parseInt(f[2]+f[1]+f[0]);
var y =parseInt(t[2]+t[1]+t[0]);
if(x > y){
alert("date1 is after date2");
}
else if(x < y){
alert("date1 is before date2");
}
else{
alert("both date are same");
}