簡體   English   中英

Javascript比較兩個日期以獲得差異

[英]Javascript compare two dates to get a difference

我正在嘗試比較兩個不同的日期,以查看輸入的日期是否是今天日期的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 = 13255772630(<-或類似名稱)。

我在這里做錯什么了嗎?
不確定是否有幫助,但我的日期格式為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;
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM