How to compare date string using javascript

前端 未结 3 1473
醉梦人生
醉梦人生 2021-01-23 22:46

I have the following string value of a date, Sun Apr 07 2019 00:00:00 GMT-0300, and I need to compare with the following date form

相关标签:
3条回答
  • 2021-01-23 22:57

    Build a date from the strings and compare the days (ie number of seconds since epoch / number of seconds in a day):

    const sameDay = (dateString1, dateString2) => {
      let time1 = (new Date(dateString1)).getTime();
      let time2 = (new Date(dateString2)).getTime();
      return Math.floor(Math.abs((time1-time2))/(1000*60*60*24))==0;
    }
    
    console.log(
      sameDay('Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)','2019-04-08T03:00:00.000Z'),
      sameDay('Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)','2019-04-13T03:00:00.000Z'),
    );

    0 讨论(0)
  • 2021-01-23 23:12

    Sun Apr 07 2019 00:00:00 GMT-0300

    2019-04-08T03:00:00.000Z

    note that both are the same day

    No, they are not.

    You can convert them both to ISO string and just compare their date parts as strings (if I understood the question correctly, you want to compare date only, without time):

    function isSameDate(date1, date2) {
      const [d1, ] = (new Date(date1)).toISOString().split('T');
      const [d2, ] = (new Date(date2)).toISOString().split('T');
      return d1 === d2;
    }
    
    0 讨论(0)
  • 2021-01-23 23:15

    Convert all the values to Date objects and compare those. Use a framework/library to do it, because parsing strings to dates manually has lots of places where it can go wrong.

    Currently you are comparing the literal Strings. Because neither "2019-04-08T03:00:00.000Z", nor "2019-04-13T03:00:00.000Z" match "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)", your second if statement fails.

    0 讨论(0)
提交回复
热议问题