[英]How can I check if a date is greater than the other?
I have 2 dates. 我有两个约会。 Both are in yyyy-mm-dd
format. 两者均为yyyy-mm-dd
格式。 I applied a simple check that if 我应用了一个简单的检查
if ('2017-01-15' > '2016-12-15') {
return true;
} else {
return false;
}
But it is giving me a syntax error. 但这给了我一个语法错误。 What should I do? 我该怎么办?
Given the format of the date string and your code structure, what you have should be working. 给定日期字符串的格式和您的代码结构,那么您应该已经在做什么。 If you're getting an error, check that it's coming from the section of code you've shown in your question. 如果遇到错误,请检查该错误是否来自问题中显示的代码部分。
That being said, you can improve the code by changing the strings to Date objects before comparing them. 话虽如此,您可以通过在比较字符串之前将字符串更改为Date对象来改进代码。 You can also shorten the code by just returning the result of the comparison. 您还可以仅通过返回比较结果来缩短代码。 Try this: 尝试这个:
function dateComparison() { return new Date('2017-01-15') > new Date('2016-12-15'); } console.log(dateComparison());
As per the MDN 根据MDN
The return statement ends function execution and specifies a value to be returned to the function caller. return语句结束函数执行并指定要返回给函数调用者的值。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/return
So you must be getting this error if you are not using the if condition within a function. 因此,如果未在函数中使用if条件,则必须得到此错误。
Operators like ==, !=, ===, and !==
require you to use date.getTime()
like this: 像==, !=, ===, and !==
这样的运算符要求您使用date.getTime()
像这样:
var x = new Date('2017-01-15');
var y = new Date('2016-12-15');
var same = x.getTime() === y.getTime();
var notSame = x.getTime() !== y.getTime();
您可以使用moment.js库来帮助您实现:
return moment('2017-01-15').format('YYYY-MM-DD') > moment('2016-12-15').format('YYYY-MM-DD');
You could convert them to Date
objects and then compare. 您可以将它们转换为Date
对象,然后进行比较。
var dateStrA = "2017-01-15 00:00:00";
var dateStrB = "2016-12-15 00:00:00";
if (new Date(dateStrA) > new Date(dateStrB))
{
...
}
else
{
...
}
Comparing using equals, such as ===
will not work on Date
objects. 使用等号(例如===
进行比较将不适用于Date
对象。 You can also use Date.compare()
您也可以使用Date.compare()
Try this...worked for me.
var startDate = "2019-03-23"; var endDate = "2019-03-24"; if(Date.parse(endDate) >= Date.parse(startDate)) { console.log('endDate is greater'); } else { console.log('startDate is greater'); }
你可以试试这个
if(d1.getTime()>d2.getTime())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.