如何用moment.js比较两个日期

时间:2019-01-05 18:19:45

标签: javascript momentjs

我有三种不同类型的日期,我无法比较它们。

let withOneDayLess = moment().subtract(1, "days").format("DD-MM-YYYY");
//let justnow = moment().format("DD-MM-YYYY");
let takenAt = moment.unix(story.takenAt).format("DD-MM-YYYY");

if(takenAt >= withOneDayLess){
    Arrstory.push(story)
     console.log(takenAt," - " ,withOneDayLess)
  };

story.takenAt是UNIX中一个故事的日期,我需要昨天和今天之间的所有故事,但是我认为if仅比较了第一个数字,给我的故事不符合要求

1 个答案:

答案 0 :(得分:2)

我假设您的currentDate变量也被创建为.format("DD-MM-YYYY")方法调用...所以您不比较日期-您在比较字符串。比较日期以获得所需的结果:

var d1 = moment().subtract(1,"days");
var d2 = moment();
if (d1 < d2) alert(d1);


let currentDate = moment();
let story = { takenAt: 1746713004 };
let withOneDayLess = moment().subtract(1, "days").format("DD-MM-YYYY");
let justnow = moment().format("DD-MM-YYYY");
let takenAt = moment.unix(story.takenAt).format("DD-MM-YYYY");

// this will never alert - typeof(takenAt) === "string" and the comparison
// "08-05-2025" is not >= "Sat Jan 05 2019 10:36:11 GMT-0800" as currentDate
// get coerced to a string to do the comparison if it's not a string already.
if(takenAt >= currentDate){
   alert("takenAt is later than currentDate");
}

// this WILL work because it's comparing a moment date to a moment date directly.
takenAt = moment.unix(story.takenAt);
if(takenAt >= currentDate){
   alert(takenAt.format("DD-MM-YYYY") + " is later than " + currentDate.format("DD-MM-YYYY"));
}