javascriptangulardatecross-browserdays

how to make calculation of days based on 2 dates using angular12


i am using angular12, here calculation of days based on 2 dates works fine with chrome, but the same thing fails in firefox.

TS: Using Moment, gives invalid date error under firefox:

 getDaysCount(firstDate: any, secondDate: any) {
    let first = moment(firstDate, 'MM-DD-YYYY');
    let second = moment(secondDate, 'MM-DD-YYYY');
    return second.diff(first, 'days');
  }

console.log(this.getDaysCount('11-12-2022', '11-14-2022));

var Difference_In_Days = Math.ceil(Math.abs(secondDate - firstDate) / (1000 * 60 * 60 * 24));

this gives NAN in firefox but gives 2 in chrome.


Solution

  • Take a look at this answer. Firefox requires the date in yyyy-mm-dd format. If you make the change, it works in both Firefox and Chrome.

    FYI, you cannot use Math.ceil on strings, you need to convert them to milliseconds first.

    getDaysCount(firstDate: any, secondDate: any) {
        const firtDateMs = (new Date(firstDate)).getTime();
        const secondDateMs = (new Date(secondDate)).getTime();
        console.log('First date: ' + firstDate, 'In ms:' + firtDateMs);
        console.log('Second date: ' + firstDate, 'In ms:' + secondDateMs);
        const Difference_In_Days = Math.ceil(Math.abs(firtDateMs - secondDateMs) / (1000 * 60 * 60 * 24));
        console.log("Difference_In_Days: ", Difference_In_Days);
      }
    

    To include negative numbers in the result, remove Math.abs from the function.

    const Difference_In_Days = Math.ceil((firtDateMs - secondDateMs) / (1000 * 60 * 60 * 24));
    

    Firefox console: enter image description here

    Chrome console:

    enter image description here