首页 > 解决方案 > MomentJS 返回意外结果

问题描述

不确定我的日期和 moment.js 做错了什么。

我有以下代码:

function(value) {                        
  const startDate = moment(this.parent.startDate).format("DD/MM/YYYY")
  const endDate = moment(value).format("DD/MM/YYYY")
  console.log("SE",startDate,endDate)
  return moment(startDate).isSameOrBefore(moment(endDate))
}

我的 console.log 的输出startDateendDate是:

SE 15/08/2021 19/08/2021

但是由于某种原因,当调用这个函数时,它是说我的:

End date must be greater than or equal to start date

根据我的return moment(startDate).isSameOrBefore(moment(endDate)),不应该是结束日期19/08/2021在开始日期之后的情况15/08/2021

我错过了什么?

标签: javascriptdatemomentjs

解决方案


比较原始日期,而不是格式化日期,因为 moment.js 不知道它们的DD/MM/YYYY格式。

function(value) {                        
  const startDate = moment(this.parent.startDate).format("DD/MM/YYYY")
  const endDate = moment(value).format("DD/MM/YYYY")
  console.log("SE",startDate,endDate)
  return moment(this.parent.startDate).isSameOrBefore(moment(value))
}

推荐阅读