javascript 如何使用angular12根据2个日期计算天数

kognpnkq  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(150)

我正在使用angular 12,在这里计算天的基础上,2个日期工程罚款与铬,但同样的事情失败,在火狐。
TS:使用Moment,在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');
  }

“2022年11月12日”);

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

这在火狐中给出了NAN,但在Chrome中给出了2。

ldioqlga

ldioqlga1#

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:

相关问题