简体   繁体   English

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

[英]Comparing simple date strings (e.g. console.log(“24.3.2018” < “20.3.2017”))

I wanted to know if the method of comparing two string values of dates, mentioned in the title, is legit. 我想知道标题中提到的比较两个日期字符串值的方法是否合法。 I have tried multiple different versions of comparison and they all seem to work. 我尝试了多种不同版本的比较,它们似乎都可以工作。

 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 

Thank you! 谢谢!

You can parse your String date to Date Object and compare : 您可以将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 

WARNING ! 警告 !

In some browsers, months or days with no leading zeroes may produce an error: 在某些浏览器中,几个月或几天没有前导零可能会产生错误:

var d = new Date("2015-3-25");

So better to prepend zero in month and days in case of length is 1 . 因此,最好在长度为1情况下在月和日中添加zero

you can compare the date values in javascript like this : 您可以像这样在javascript中比较日期值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM