有人能提出一种方法来比较两个大于、小于和过去不使用JavaScript的日期的值吗?值将来自文本框。


当前回答

“一些”发布的代码的改进版本

/* 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));

其他回答

与往常一样比较<和>,但涉及==或==的任何内容都应使用+前缀。像这样:

const x=新日期(‘2013-05-23’);const y=新日期(‘2013-05-23’);//小于、大于即可:console.log('x<y',x<y);//假的console.log('x>y',x>y);//假的console.log('x<=y',x<=y);//真的console.log('x>=y',x>=y);//真的console.log('x===y',x===y);//假的,哎呀!//任何涉及“==”或“===”的内容都应使用“+”前缀//然后将比较日期的毫秒值console.log('+x===+y',+x===+y);//真的

这是我在一个项目中所做的,

function CompareDate(tform){
     var startDate = new Date(document.getElementById("START_DATE").value.substring(0,10));
     var endDate = new Date(document.getElementById("END_DATE").value.substring(0,10));

     if(tform.START_DATE.value!=""){
         var estStartDate = tform.START_DATE.value;
         //format for Oracle
         tform.START_DATE.value = estStartDate + " 00:00:00";
     }

     if(tform.END_DATE.value!=""){
         var estEndDate = tform.END_DATE.value;
         //format for Oracle
         tform.END_DATE.value = estEndDate + " 00:00:00";
     }

     if(endDate <= startDate){
         alert("End date cannot be smaller than or equal to Start date, please review you selection.");
         tform.START_DATE.value = document.getElementById("START_DATE").value.substring(0,10);
         tform.END_DATE.value = document.getElementById("END_DATE").value.substring(0,10);
         return false;
     }
}

在表单onsubmit上调用此项。希望这有帮助。

如果以下是您的日期格式,您可以使用此代码:

var first = '2012-11-21';
var second = '2012-11-03';
if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
   //...
}

将检查20121121号是否大于20121103号。

在比较Dates对象之前,请尝试将两者的毫秒设置为零,如Date.setMilliseconds(0);。

在某些情况下,Date对象是用javascript动态创建的,如果您继续打印Date.getTime(),您将看到毫秒数发生变化,这将阻止两个日期相等。

假设您处理的是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

如您所见,我们去掉分隔符,然后比较整数。