2017-05-03 125 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'); 
}