下面的代码有什么问题?
也许只比较日期而不是时间会更简单。我也不确定如何做到这一点,我搜索了一下,但我找不到我的确切问题。
顺便说一句,当我在警报中显示这两个日期时,它们显示完全相同。
我的代码:
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);
}
});
有没有一种更简单的方法来比较日期而不包括时间?
var fromdate = new Date(MM/DD/YYYY);
var todate = new Date(MM/DD/YYYY);
if (fromdate > todate){
console.log('False');
}else{
console.log('True');
}
如果你的日期格式不同,那么使用moment.js库转换你的日期格式,然后使用上面的代码来比较两个日期
例子:
如果您的日期是“DD/MM/YYYY”,并希望将其转换为“MM/DD/YYYY”,请参阅下面的代码示例
var newfromdate = new Date(moment(fromdate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newfromdate);
var newtodate = new Date(moment(todate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newtodate);
在看到这个问题的同时,我决定发布另一个解决方案,因为我觉得它不太令人满意,至少对我的需求来说:
我曾经用过这样的东西:
var currentDate= new Date().setHours(0,0,0,0);
var startDay = new Date(currentDate - 86400000 * 2);
var finalDay = new Date(currentDate + 86400000 * 2);
这样,我就可以用我想要的格式来处理这些日期。但这只是为了我的需要,但我还是决定张贴它,也许它会帮助到别人
使用javascript,您可以将现有日期对象的时间值设置为零,然后解析回日期。解析回Date后,两者的Time值都为0,您可以进行进一步的比较
let firstDate = new Date(mydate1.setHours(0, 0, 0, 0));
let secondDate = new Date(mydate2.setHours(0, 0, 0, 0));
if (selectedDate == currentDate)
{
console.log('same date');
}
else
{
console.log(`not same date`);
}
我是这样做的:
var myDate = new Date($('input[name=frequency_start]').val()).setHours(0,0,0,0);
var today = new Date().setHours(0,0,0,0);
if(today>myDate){
jAlert('Please Enter a date in the future','Date Start Error', function(){
$('input[name=frequency_start]').focus().select();
});
}