如何使用 JavaScript 計算距離下一個聖誕節還有多少天?


在本文中,您將瞭解如何使用 JavaScript 計算距離下一個聖誕節還有多少天。Date 物件用於處理日期和時間。Date 物件使用 new Date() 建立。JavaScript 將使用瀏覽器的時區並將日期顯示為完整的文字字串。

示例 1

在此示例中,我們計算時間差,不使用函式。

let todayDate = new Date();
console.log("Today's date is defined as: ", todayDate)
let christmasYear = todayDate.getFullYear();
if (todayDate.getMonth() == 11 && todayDate.getDate() > 25) {
   christmasYear = christmasYear + 1;
}

let christmasDate = new Date(christmasYear, 11, 25);
let dayMilliseconds = 1000 * 60 * 60 * 24;
let daysLeft = Math.ceil(
   (christmasDate.getTime() - todayDate.getTime()) / (dayMilliseconds)
);
console.log("
The number of days left for christmas is: ") console.log(daysLeft)

解釋

  • 步驟 1 − 定義兩個日期物件,分別為 todayDate 和 christmasDate。

  • 步驟 2 − 定義一個名為 dayMilliseconds 的變數,用於儲存一天的總毫秒數。

  • 步驟 3 − 減去兩個日期值,並將結果除以 dayMilliseconds。

  • 步驟 4 − 顯示結果。

示例 2

在此示例中,我們使用函式計算時間差。

function calculateDates(christmasDate, todayDate){
   let dayMilliseconds = 1000 * 60 * 60 * 24;
   let daysLeft = Math.ceil(
      (christmasDate.getTime() - todayDate.getTime()) /
         (dayMilliseconds)
      );
      console.log("
The number of days left for christmas is: ") console.log(daysLeft) } let todayDate = new Date(); console.log("Todays date is defined as: ", todayDate) let christmasYear = todayDate.getFullYear(); if (todayDate.getMonth() == 11 && todayDate.getDate() > 25) { christmasYear = christmasYear + 1; } let christmasDate = new Date(christmasYear, 11, 25); calculateDates(christmasDate, todayDate);

解釋

  • 步驟 1 − 定義兩個日期物件,分別為 todayDate 和 christmasDate。

  • 步驟 2 − 定義一個名為 dayMilliseconds 的變數,用於儲存一天的總毫秒數。

  • 步驟 3 − 定義一個名為 calculateDates 的函式,該函式以兩個日期值作為引數。

  • 步驟 4 − 在函式中,減去兩個日期值,並將結果除以 dayMilliseconds。

  • 步驟 5 − 顯示結果。

更新於: 2023年2月16日

710 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.