"إذا أراد العامل أن يؤدي عمله بشكل جيد، فعليه أولاً أن يشحذ أدواته." - كونفوشيوس، "مختارات كونفوشيوس. لو لينجونج"
الصفحة الأمامية > برمجة > JavaScript计算两个日期之间天数的方法

JavaScript计算两个日期之间天数的方法

نشر في 2025-04-16
تصفح:458

How to Calculate the Number of Days Between Two Dates in JavaScript?

How to Calculate the Difference Between Dates in Javascript

As you attempt to determine the difference between two dates in Javascript, consider this solution:

The code snippet below can effectively capture the number of days between two specified dates:

<pre>const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.floor(diffTime / (1000 60 60 * 24));
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");</pre>

In this approach, we employ Math.abs() to calculate the absolute difference between the two dates, taking into account their millisecond values.

Next, we divide this difference by the millisecond equivalent of a day (1000 60 60 * 24) using Math.floor() to obtain the integer number of days, discarding any fractional values.

Ultimately, this method accurately yields the total number of elapsed days between the two specified dates, regardless of their time components.

أحدث البرنامج التعليمي أكثر>

تنصل: جميع الموارد المقدمة هي جزئيًا من الإنترنت. إذا كان هناك أي انتهاك لحقوق الطبع والنشر الخاصة بك أو الحقوق والمصالح الأخرى، فيرجى توضيح الأسباب التفصيلية وتقديم دليل على حقوق الطبع والنشر أو الحقوق والمصالح ثم إرسالها إلى البريد الإلكتروني: [email protected]. سوف نتعامل مع الأمر لك في أقرب وقت ممكن.

Copyright© 2022 湘ICP备2022001581号-3