简体   繁体   中英

how compare two dates with moment.js

I have three different types of dates and I can not compare them.

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 is the date of a story in unix, and I need all the stories between yesterday and today, but I think the if compares only the first number, giving me stories that do not correspond

I'm assuming your currentDate variable is also created as a .format("DD-MM-YYYY") method call... so you're not comparing dates - you're comparing strings. Compare the dates to get your desired result:

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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM