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


当前回答

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

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

其他回答

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 str1  = document.getElementById("Fromdate").value;
var str2  = document.getElementById("Todate").value;
var dt1   = parseInt(str1.substring(0,2),10); 
var mon1  = parseInt(str1.substring(3,5),10);
var yr1   = parseInt(str1.substring(6,10),10); 
var dt2   = parseInt(str2.substring(0,2),10); 
var mon2  = parseInt(str2.substring(3,5),10); 
var yr2   = parseInt(str2.substring(6,10),10); 
var date1 = new Date(yr1, mon1, dt1); 
var date2 = new Date(yr2, mon2, dt2); 

if(date2 < date1)
{
   alert("To date cannot be greater than from date");
   return false; 
} 
else 
{ 
   alert("Submitting ...");
   document.form1.submit(); 
} 
If you are using **REACT OR REACT NATIVE**, use this and it will work (Working like charm)

如果两个日期相同,则返回TRUE,否则返回FALSE

const compareDate = (dateVal1, dateVal2) => {
        if (dateVal1.valueOf() === dateVal2.valueOf()){
            return true;
        }
        else { return false;}
    }

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

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上调用此项。希望这有帮助。

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

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