0

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.

Bhrungarajni
  • 2,415
  • 11
  • 44
  • 88

1 Answers1

1

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

Nehal
  • 13,130
  • 4
  • 43
  • 59
  • 1
    but here second date must be greater than 1st date, if second date is lesser than 1st date means i must get numbers in negative, like -1,-3 n so on – Bhrungarajni Dec 01 '22 at 18:54
  • `firstDate - secondDate` is wrapped within `Math.abs`, which always return you positive number. If you want negative numbers, than remove the `Math.abs` from the function. – Nehal Dec 01 '22 at 19:58