比较简单的日期字符串(例如console.log(“ 24.3.2018” <“ 20.3.2017”))

时间:2018-08-06 08:16:42

标签: javascript date comparison

我想知道标题中提到的比较两个日期字符串值的方法是否合法。我尝试了多种不同版本的比较,它们似乎都可以工作。

console.log("23.3.2018" > "24.3.2018")
//VM16380:1 false
//undefined
console.log("23.3.2018" < "24.3.2018")
//VM16381:1 true
//undefined
console.log("24.3.2017" < "24.3.2018")
//VM16384:1 true
//undefined
console.log("24.3.2018" < "20.3.2017")
//VM16385:1 false

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以将<style name="MyCustomStyle" parent="android:Widget.???"/> 解析为String date并进行比较:

Date Object

  

警告!

     

在某些浏览器中,几个月或几天没有前导零可能会产生错误:

     

function CompareDate(dateStr1,dateStr2) { var dateArry1 = dateStr1.split("."); var dateArry2 = dateStr2.split("."); //JavaScript counts months from 0 index so we have to do -1:January - 0, February - 1, and so on..... var dateOne = new Date(dateArry1[2], dateArry1[1]-1, dateArry1[0]); //Year, Month, Date var dateTwo = new Date(dateArry2[2], dateArry2[1]-1, dateArry2[0]); //Year, Month, Date if (dateOne > dateTwo) { console.log("Date One is greather then Date Two."); return true; }else if(dateOne < dateTwo) { console.log("Date Two is greather then Date One."); return false; }else if(dateOne.toDateString() === dateTwo.toDateString()) { console.log("Date are same."); return false; } return false; } console.log(CompareDate("23.3.2018","24.3.2018")); //VM16380:1 false //undefined console.log(CompareDate("23.3.2018","24.3.2018")); //VM16381:1 true //undefined console.log(CompareDate("24.3.2017", "24.3.2018")); //VM16384:1 true //undefined console.log(CompareDate("24.03.2018" , "20.3.2017")); console.log(CompareDate("24.3.2018" , "24.03.2018")); //VM16385:1 false

     

因此,如果长度为var d = new Date("2015-3-25");,最好在月份和日期前加上zero

答案 1 :(得分:0)

您可以像这样比较javascript中的日期值:

var start= new Date('2018.3.23');
var end= new Date('2018.3.24');
 if (start < end) 
 {
  console.log(true);
 }