返回課程

距離明天還有幾秒?

重要性:5

建立一個函式 `getSecondsToTomorrow()`,傳回距離明天的秒數。

例如,如果現在是 `23:00`,則

getSecondsToTomorrow() == 3600

附註:函式應可在任何一天執行,「今天」並非硬編碼。

若要取得距離明天的毫秒數,我們可以從「明天 00:00:00」減去目前的日期。

首先,我們產生那個「明天」,然後執行

function getSecondsToTomorrow() {
  let now = new Date();

  // tomorrow date
  let tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1);

  let diff = tomorrow - now; // difference in ms
  return Math.round(diff / 1000); // convert to seconds
}

其他解答

function getSecondsToTomorrow() {
  let now = new Date();
  let hour = now.getHours();
  let minutes = now.getMinutes();
  let seconds = now.getSeconds();
  let totalSecondsToday = (hour * 60 + minutes) * 60 + seconds;
  let totalSecondsInADay = 86400;

  return totalSecondsInADay - totalSecondsToday;
}

請注意,許多國家有夏令時間 (DST),因此可能會有 23 或 25 小時的天數。我們可能希望分別處理這些天數。