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


当前回答

function datesEqual(a, b)
{
   return (!(a>b || b>a))
}

其他回答

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

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

通过Moment.js

Jsfidle:http://jsfiddle.net/guhokemk/1/

function compare(dateTimeA, dateTimeB) {
    var momentA = moment(dateTimeA,"DD/MM/YYYY");
    var momentB = moment(dateTimeB,"DD/MM/YYYY");
    if (momentA > momentB) return 1;
    else if (momentA < momentB) return -1;
    else return 0;
}

alert(compare("11/07/2015", "10/07/2015"));

如果dateTimeA大于dateTimeB,则该方法返回1

如果dateTimeA等于dateTimeB,则该方法返回0

如果dateTimeA小于dateTimeB,则该方法返回-1

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

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。

减去两个日期,得到以毫秒为单位的差值,如果得到0,则是相同的日期

function areSameDate(d1, d2){
    return d1 - d2 === 0
}