下面的代码有什么问题?

也许只比较日期而不是时间会更简单。我也不确定如何做到这一点,我搜索了一下,但我找不到我的确切问题。

顺便说一句,当我在警报中显示这两个日期时,它们显示完全相同。

我的代码:

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);
    }
});

有没有一种更简单的方法来比较日期而不包括时间?


当前回答

这个怎么样?

Date.prototype.withoutTime = function () {
    var d = new Date(this);
    d.setHours(0, 0, 0, 0);
    return d;
}

它允许你像这样比较日期的日期部分,而不影响变量的值:

var date1 = new Date(2014,1,1);
new Date().withoutTime() > date1.withoutTime(); // true

其他回答

我知道这个问题已经有人回答了,这可能不是最好的方法,但在我的情况下,它工作得很好,所以我想它可能会帮助像我这样的人。

如果你有日期字符串为

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()的更多信息在这里参考

快乐的鳕鱼。

确保你用一个4位数的年份构造userDate作为setFullYear(10,…)!== setFullYear(2010,…)。

我是这样做的:

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();
    });
}

使用Moment.js

如果您可以选择包含第三方库,那么绝对值得一看Moment.js。它使使用Date和DateTime变得非常非常容易。

例如,查看一个Date是否紧跟在另一个Date之后,但排除它们的时间,你会这样做:

var date1 = new Date(2016,9,20,12,0,0); // October 20, 2016 12:00:00
var date2 = new Date(2016,9,20,12,1,0); // October 20, 2016 12:01:00

// Comparison including time.
moment(date2).isAfter(date1); // => true

// Comparison excluding time.
moment(date2).isAfter(date1, 'day'); // => false

传递给isAfter的第二个参数是进行比较的精度,可以是年、月、周、日、小时、分钟或秒中的任何一个。

在两个日期上都使用toDateString()即可。toDateString不包括时间,因此对于同一日期的两次,值将相等,如下所示。

var d1 = new Date(2019,01,01,1,20)
var d2 = new Date(2019,01,01,2,20)
console.log(d1==d2) // false
console.log(d1.toDateString() == d2.toDateString()) // true

显然,在这个问题上其他地方表达的一些关于时区的担忧是有效的,但在许多情况下,这些是不相关的。