Javascript比较两个日期以获得差异

Javascript compare two dates to get a difference

本文关键字:日期 两个 比较 Javascript      更新时间:2023-09-26

我试图比较两个不同的日期,看看输入的日期是否在今天的7天后。我在谷歌上搜索了一下,得出了这个:

function val_date(input){
    var date = new Date(input);
    date = date.getTime() / 1000;
    var timestamp = new Date().getTime() + (7 * 24 * 60 * 60 * 1000)
    window.alert("Date: "+date + " = N_Date: "+timestamp);
    if(timestamp > date || timestamp === date){
        // The selected time is less than 7 days from now
        return false;
    }
    else if(timestamp < date){
    // The selected time is more than 7 days from now
        return true;
    }
    else{
    // -Exact- same timestamps.
        return false;
    }
}

我正在使用提醒,以便检查我的进度,以确保日期不同。警报的输出只是说:

日期:NaN=N_Date=132555772630(<-或类似的东西)。

我是不是做错了什么
不确定它是否有帮助,但我的日期格式是DD-MM-YYYY

如果您正在比较日期并且不想包括时间,您可以使用以下内容:

// dateString is format DD-MM-YYYY
function isMoreThan7DaysHence(dateString) {
    // Turn string into a date object at 00:00:00
    var t = dateString.split('-');
    var d0 = new Date(t[2], --t[1], t[0]);
    // Create a date for 7 days hence at 00:00:00
    var d1 = new Date();
    d1.setHours(0, 0, 0, 0);
    d1.setDate(d1.getDate() + 7);
    return d0 >= d1;
}

请注意,今天日期的小时数必须为零。

日期:NaN因为您传递给日期创建的字符串不可能创建日期


尝试

小提琴演示

Date.prototype.addDays = function (days) {
    this.setDate(this.getDate() + days);
    return this;
};
function val_date(input) {
    var inputDate = new Date(input);
    var dateWeek = new Date().addDays(7);
    console.log(inputDate, dateWeek);
    if (inputDate < dateWeek) {
        // The selected time is less than 7 days from now
        return false;
    } else {
        // The selected time is more than 7 days from now
        return true;
    }
}

使用moment.js:

moment([2013, 2, 29]).fromNow();

这很常见,如果要操作日期,可能需要使用Javascript库。有一个优秀的名为moment.js的

使用这个你会做一些类似的事情:

moment().add('days', 7)

寻找未来的一周。

假设输入是一个有效的Javascript Date对象,您可以尝试:

function dateDifference(oldDate) {
    var currentDate = new Date();
    var difference = currentDate - oldDate; //unit: milliseconds
    var numDays = 7;
    var threshHoldTime = numDays * (24 * 60 * 60 * 1000); //seven days in milliseconds
    if (difference > threshHoldTime ) {
        console.log("The difference is greateer then then 7 days");
    }
    else {
        console.log("the date is not enough: " + difference);
    }
}

像这样尝试

var date = new Date(input).getTime(); // Get the milliseconds
var today = new Date();    
//You can't compare date, 
//so convert them to milliseconds
today = new Date(today.setDate(today.getDate() + 7)).getTime(); 
if (inputDate < today) {
    // The selected time is less than 7 days from now
    return false;
 } else if{ ()
    // -Exact- same timestamps.
    return false;
 }
 else {
    // The selected time is more than 7 days from now
    return true;
 }