将 moment.js 对象与来自 JSON 响应的时间戳进行比较

Comparing a moment.js obect to a timestamp from JSON response

我正在尝试将时刻对象(30 天前)与给定的时间戳进行比较。 isBefore 和 isAfter 都返回 false。我不确定哪里出错了?

var startdate = moment.utc().subtract(30,'days')

var RequestedDate = moment.utc('14/12/2021, 11:26')

var isbefore = startdate.isBefore(RequestedDate)
var isafter = startdate.isAfter(RequestedDate)

console.log(isafter)
console.log(isbefore)

根据 a fiddle of your code 中发出的错误,请求的日期格式不正确:

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. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

如果您能够使用 "Date + Format" constructor, then you can parse something like this:

var RequestedDate = moment.utc('14/12/2021, 11:26', 'D/M/Y, H:m', true)
// "Tue Dec 14 2021 11:26:00 GMT+0000"

注意严格模式的使用,如文档所示:

You may get unexpected results when parsing both date and time. The below example may not parse as you expect:

moment('24/12/2019 09:15:00', "DD MM YYYY hh:mm:ss");