」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 JavaScript 準確計算兩個日期之間的年、月、日差異?

如何使用 JavaScript 準確計算兩個日期之間的年、月、日差異?

發佈於2024-12-11
瀏覽:625

How Can I Accurately Calculate the Difference Between Two Dates in Years, Months, and Days Using JavaScript?

在JavaScript 中確定年、月、日的日期差異

確定兩個日期之間年、月、日的差異可以由於僅提供一個單位(年、月或日)差異的解決方案不一致或不準確,JavaScript中存在挑戰性

這裡有一個更全面的解決方案,考慮了平年和閏年以及月份之間的確切天數差異:

today = new Date();
past = new Date(2010, 05, 01); // Equivalent to June 1, 2010

function calcDate(date1, date2) {
  // Calculate the difference in milliseconds
  var diff = Math.floor(date1.getTime() - date2.getTime());

  // Convert milliseconds to days
  var day = 1000 * 60 * 60 * 24;
  var days = Math.floor(diff / day);

  // Calculate months and years from days
  var months = Math.floor(days / 31);
  var years = Math.floor(months / 12);

  // Format the message
  var message = date2.toDateString();
  message  = " was ";
  message  = days   " days ";
  message  = months   " months ";
  message  = years   " years ago \n";

  return message;
}

console.log(calcDate(today, past));
// Output: Tue Jun 01 2010 was 1143 days 36 months 3 years ago

此解決方案透過將毫秒數轉換為天數,然後進一步從日期中推導出月份和年份,從而準確計算兩個日期之間的差異總天數。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3