下面的代码有什么问题?
也许只比较日期而不是时间会更简单。我也不确定如何做到这一点,我搜索了一下,但我找不到我的确切问题。
顺便说一句,当我在警报中显示这两个日期时,它们显示完全相同。
我的代码:
window.addEvent('domready', function() {
var now = new Date();
var input = $('datum').getValue();
var dateArray = input.split('/');
var userMonth = parseInt(dateArray[1])-1;
var userDate = new Date();
userDate.setFullYear(dateArray[2], userMonth, dateArray[0], now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
if (userDate > now)
{
alert(now + '\n' + userDate);
}
});
有没有一种更简单的方法来比较日期而不包括时间?
我知道这个问题已经有人回答了,这可能不是最好的方法,但在我的情况下,它工作得很好,所以我想它可能会帮助像我这样的人。
如果你有日期字符串为
String dateString="2018-01-01T18:19:12.543";
你只是想将date部分与JS中的另一个date对象进行比较,
var anotherDate=new Date(); //some date
然后你必须使用new Date("2018-01-01T18:19:12.543")将字符串转换为Date对象;
诀窍在这里:-
var valueDate =new Date(new Date(dateString).toDateString());
return valueDate.valueOf() == anotherDate.valueOf(); //here is the final result
我已经使用了JS的Date对象的toDateString(),它只返回日期字符串。
注意:不要忘记在比较日期时使用. valueof()函数。
关于.valeOf()的更多信息在这里参考
快乐的鳕鱼。
这个JS将在设置日期之后更改内容
这里有同样的东西,但在w3schools上
date1 = new Date()
date2 = new Date(2019,5,2) //the date you are comparing
date1.setHours(0,0,0,0)
var stockcnt = document.getElementById('demo').innerHTML;
if (date1 > date2){
document.getElementById('demo').innerHTML="yes"; //change if date is > set date (date2)
}else{
document.getElementById('demo').innerHTML="hello"; //change if date is < set date (date2)
}
<p id="demo">hello</p> <!--What will be changed-->
<!--if you check back in tomorrow, it will say yes instead of hello... or you could change the date... or change > to <-->
比较日期和时间:
var t1 = new Date(); // say, in ISO String = '2022-01-21T12:30:15.422Z'
var t2 = new Date(); // say, in ISO String = '2022-01-21T12:30:15.328Z'
var t3 = t1;
比较2个日期对象的毫秒级:
console.log(t1 === t2); // false - Bcos there is some milliseconds difference
console.log(t1 === t3); // true - Both dates have milliseconds level same values
仅根据日期比较2个日期对象(忽略任何时间差):
console.log(t1.toISOString().split('T')[0] === t2.toISOString().split('T')[0]);
// true; '2022-01-21' === '2022-01-21'
仅通过时间(ms)比较2个日期对象(忽略任何日期差异):
console.log(t1.toISOString().split('T')[1] === t3.toISOString().split('T')[1]);
// true; '12:30:15.422Z' === '12:30:15.422Z'
以上2个方法使用toISOString()方法,因此您无需担心国家之间的时区差异。