[英]how to make calculation of days based on 2 dates using angular12
我正在使用 angular12,這里基於 2 個日期的天數計算在 chrome 上工作正常,但同樣的事情在 firefox 中失敗了。
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');
}
console.log(this.getDaysCount('11-12-2022', '11-14-2022));
var Difference_In_Days = Math.ceil(Math.abs(secondDate - firstDate) / (1000 * 60 * 60 * 24));
這在 firefox 中給出 NAN,但在 chrome 中給出 2。
看看這個答案。 Firefox 需要yyyy-mm-dd
格式的日期。 如果您進行更改,它在 Firefox 和 Chrome 中都有效。
僅供參考,您不能在字符串上使用Math.ceil
,您需要先將它們轉換為毫秒。
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);
}
要在結果中包含負數,請從 function 中刪除Math.abs
。
const Difference_In_Days = Math.ceil((firtDateMs - secondDateMs) / (1000 * 60 * 60 * 24));
鉻控制台:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.