簡體   English   中英

如何設置計時器以顯示一天結束還剩多少時間?

[英]How do I set the timer to show how much time is left for the day to end?

我想用這個計時器來顯示巴西巴西利亞時間結束一天還有多少小時,我無法用 gethours 形成一些東西

{% assign productTags = product.tags %}  
{% if productTags contains 'contador' %}
<script>
  function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
      minutes = parseInt(timer / 60, 10)
      seconds = parseInt(timer % 60, 10);

      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      display.getHours();

      if (--timer < 0) {
        timer = duration;
      }
    }, 1000);
  }

  window.onload = function () {
    var fiveMinutes = 60 * 29.5,       
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
  };

我可以用這段代碼做到這一點嗎?

解決這個問題的一種方法是使用備受喜愛日期 API來確定今天和明天的日歷日期。

您可以使用以下方法獲取自紀元以來的今天日期(以毫秒為單位):

const now = new Date()


// Sun Dec 11 2022 13:21:03 GMT-XXXX (Your Time Zone)

然后你可以得到自 Epoch 以來的毫秒數

const nowMsSinceEpoch = now.getTime()

// 1670793708603

這是解決問題的基礎。 如果你能找到今天的毫秒數和明天的 00:00,你可以比較兩者:

let tomorrow = new Date()
tomorrow.setDate(now.getDate() + 1)
tomorow.setHours(0,0,0,0)

// Mon Dec 12 2022 00:00:00 GMT-XXXX (Your Time Zone)

在此階段,您已准備好了解明天和今天的區別:


const differenceMs = tomorrow.getTime() - now.getTime()


通過從一個與紀元相關的時間戳中減去另一個與紀元相關的時間戳,您現在有了差異,並且您現在可以准確地計算出時間。 現在這只是一個算術問題。 您將需要確定一個小時內有多少毫秒,並且您將尋求您希望以何種方式對數字進行四舍五入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM