【问题标题】:moment.js compare not working as expected [duplicate]moment.js 比较未按预期工作[重复]
【发布时间】:2018-06-22 13:43:24
【问题描述】:

我需要比较两个日期以检查所选日期是否小于今天。

//taking current time

    var orignalDateFromAPI = moment();
    var selectedDate = moment(orignalDateFromAPI,"YYYY-MM-DD");

    console.log(selectedDate.format("DD-MM-YYYY"));

    var nativeDate = new Date(selectedDate);
    var parsedDate= moment(nativeDate,"YYYY-MM-DD");

    console.log(parsedDate.format("DD-MM-YYYY"));

    console.log(selectedDate.isSame(parsedDate)); //true
    console.log(selectedDate == parsedDate); //false

为什么第一条语句打印true,而第二条语句打印false? 有没有更好的方法来检查某个日期是否小于或等于另一个日期?

编辑:我去了标记为重复的问题,但找不到与 moment.js 比较相关的任何答案。
我浏览了 moment.js 文档并找到了is same or before。我认为这会很好。有什么注意事项吗?

【问题讨论】:

  • 可以使用; momentObj.isBefore()momentObj.isAfter()
  • 可以直接比较时间戳;对象仅在 JS 中通过引用进行比较。对于less than or equal!isAfter 就足够了。
  • 我不认为这个问题是重复的,因为 OP 询问他为什么不能使用==。而不是为什么不能比较对象

标签: javascript datetime momentjs datetime-format


【解决方案1】:

===== 不能用于比较 object 类型的变量。如果您看到 selectedDateparsedDate 的类型,则它是 object 类型(属于 Moment)。所以,你不能使用==。相反,您必须使用 MomentJS 的isSame 函数。

var orignalDateFromAPI = moment();
var selectedDate = moment(orignalDateFromAPI,"YYYY-MM-DD");

console.log(selectedDate.format("DD-MM-YYYY"));

var nativeDate = new Date(selectedDate);
var parsedDate= moment(nativeDate,"YYYY-MM-DD");

console.log(parsedDate.format("DD-MM-YYYY"));

console.log('typeof selectedDate ' + typeof selectedDate);
console.log(selectedDate.isSame(parsedDate)); //true
console.log(selectedDate == parsedDate); //false
<script src="https://momentjs.com/downloads/moment.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多