简体   繁体   中英

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.

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: 在此处输入图像描述

Chrome console:

在此处输入图像描述

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