2017-05-03 56 views
-1

此流星服務器代碼嘗試查找給定的日期字符串DD/MM/YYYY是否在過去14天內。比較日期和時間js

let date = '03/05/2017'; //DD/MM/YYYY 

    let dayStart = moment().subtract(14, 'days').format('DD/MM/YYYY'); 

    if (moment(date).isBefore(dayStart)) { 
    console.log('before'); 
    } else { 
    console.log('after'); 
    } 

這工作,但我得到的控制檯錯誤:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

任何建議如何解決它,所以它工作沒有錯誤? thx

+2

在警告信息的鏈接告訴你到底要做什麼。您需要在'if'行中構建日期時指定使用的格式。 –

回答

1

您正在計算一個日期,將它寫入一個字符串,以未指定的(以解析時間)非標準格式解析String中的同一日期,並將其與未指定的非標準格式中的另一個日期進行比較。

相反,pass a parse format和做的時刻,而不是字符串比較:

let date = '03/05/2017'; //DD/MM/YYYY 
let dateAsMoment = moment(date, 'DD/MM/YYYY'); // specified parsed date 

let dayStart = moment().subtract(14, 'days'); // 14 days before now, as a Moment 

if (dateAsMoment.isBefore(dayStart)) { 
    console.log('before'); 
} else { 
    console.log('after'); 
}