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


当前回答

什么格式?

如果您构造了Javascript Date对象,您可以将它们减去以获得毫秒差(编辑:或只是比较它们):

js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true

其他回答

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
var date_today=new Date();
var formated_date = formatDate(date_today);//Calling formatDate Function

var input_date="2015/04/22 11:12 AM";

var currentDateTime = new Date(Date.parse(formated_date));
var inputDateTime   = new Date(Date.parse(input_date));

if (inputDateTime <= currentDateTime){
    //Do something...
}

function formatDate(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';

    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    hours   = hours < 10 ? '0'+hours : hours ;

    minutes = minutes < 10 ? '0'+minutes : minutes;

    var strTime = hours+":"+minutes+ ' ' + ampm;
    return  date.getFullYear()+ "/" + ((date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) :
    (date.getMonth()+1) ) + "/" + (date.getDate() < 10 ? "0"+date.getDate() :
    date.getDate()) + " " + strTime;
}

为了在众多现有选项中添加另一种可能性,您可以尝试:

if (date1.valueOf()==date2.valueOf()) .....

…这似乎对我有用。当然,你必须确保这两个日期都没有定义。。。

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....

通过这种方式,我们可以确保如果两者都未定义,或者。。。

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....

…如果你希望他们不平等。

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

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

什么格式?

如果您构造了Javascript Date对象,您可以将它们减去以获得毫秒差(编辑:或只是比较它们):

js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true