有人能提出一种方法来比较两个大于、小于和过去不使用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));

其他回答

var date = new Date(); // will give you todays date.

// following calls, will let you set new dates.
setDate()   
setFullYear()   
setHours()  
setMilliseconds()   
setMinutes()    
setMonth()  
setSeconds()    
setTime()

var yesterday = new Date();
yesterday.setDate(...date info here);

if(date>yesterday)  // will compare dates

我对这个问题的简单回答

checkDisabled(date) {
    const today = new Date()
    const newDate = new Date(date._d)
    if (today.getTime() > newDate.getTime()) {
        return true
    }
    return false
}
       

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

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

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

嗨,这是我比较日期的代码。在我的情况下,我正在检查是否允许选择过去的日期。

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;

如果两个日期的格式都是“YYYY-MM-DD”,则可以跳过Date对象,直接比较字符串。

这是因为JS中字符串的比较方式

let date1 = '2022-12-13';
let date2 = '2022-02-13';

console.log(`${date1} > ${date2}`, date1 > date2);
console.log(`${date1} < ${date2}`, date1 < date2);
console.log(`${date1} == ${date2}`, date1 == date2);