как сравнить две даты с moment.js - PullRequest
0 голосов
/ 05 января 2019

У меня есть три разных типа дат, и я не могу их сравнить.

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 голосов
/ 05 января 2019

Я предполагаю, что ваша переменная 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"));
}
...