有人能提出一种方法来比较两个大于、小于和过去不使用JavaScript的日期的值吗?值将来自文本框。


当前回答

通过Moment.js

Jsfidle:http://jsfiddle.net/guhokemk/1/

function compare(dateTimeA, dateTimeB) {
    var momentA = moment(dateTimeA,"DD/MM/YYYY");
    var momentB = moment(dateTimeB,"DD/MM/YYYY");
    if (momentA > momentB) return 1;
    else if (momentA < momentB) return -1;
    else return 0;
}

alert(compare("11/07/2015", "10/07/2015"));

如果dateTimeA大于dateTimeB,则该方法返回1

如果dateTimeA等于dateTimeB,则该方法返回0

如果dateTimeA小于dateTimeB,则该方法返回-1

其他回答

尝试使用此代码

var f =date1.split("/");

var t =date2.split("/");

var x =parseInt(f[2]+f[1]+f[0]);

var y =parseInt(t[2]+t[1]+t[0]);

if(x > y){
    alert("date1 is after date2");
}

else if(x < y){
    alert("date1 is before date2");
}

else{
    alert("both date are same");
}

仅比较日期(忽略时间分量):

Date.prototype.sameDay = function(d) {
  return this.getFullYear() === d.getFullYear()
    && this.getDate() === d.getDate()
    && this.getMonth() === d.getMonth();
}

用法:

if(date1.sameDay(date2)) {
    // highlight day on calendar or something else clever
}

我不再建议修改内置对象的原型。请尝试以下操作:

函数为SameDay(d1,d2){return d1.getFullYear()==d2.getFullYear()&&d1.getDate()==d2.getDate&&d1.getMonth()==d2.getMont();}console.log(isSameDay(新日期(‘2021 1月15日02:39:53 GMT-0800’),新日期(’2021 1月15号23:39:53格林威治时间-0800’));console.log(isSameDay(新日期(2021 1月15日10:39:53 GMT-0800),新日期(2021 1月16日10:39:33 GMT-0800'));

注意:将返回您所在时区的年/月/日;如果您想检查两个日期是否在不同时区的同一天,我建议使用时区感知库。

e.g.

> (new Date('Jan 15 2021 01:39:53 Z')).getDate()  // Jan 15 in UTC
14  // Returns "14" because I'm in GMT-08
If you are using **REACT OR REACT NATIVE**, use this and it will work (Working like charm)

如果两个日期相同,则返回TRUE,否则返回FALSE

const compareDate = (dateVal1, dateVal2) => {
        if (dateVal1.valueOf() === dateVal2.valueOf()){
            return true;
        }
        else { return false;}
    }

为了在众多现有选项中添加另一种可能性,您可以尝试:

if (date1.valueOf()==date2.valueOf()) .....

…这似乎对我有用。当然,你必须确保这两个日期都没有定义。。。

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....

通过这种方式,我们可以确保如果两者都未定义,或者。。。

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....

…如果你希望他们不平等。

为了从JavaScript中的自由文本创建日期,您需要将其解析为Date对象。

您可以使用Date.parse(),它获取自由文本并尝试将其转换为新的日期,但如果您能够控制页面,我建议使用HTML选择框或日期选择器,例如YUI日历控件或jQueryUI日期选择器。

正如其他人所指出的,一旦你有了日期,你就可以使用简单的算术来减去日期,并将其转换为天数,方法是将数字(以秒为单位)除以一天中的秒数(60*60*24=86400)。