LoginSignup
6
8

More than 1 year has passed since last update.

javascriptで今年の残り日時(カウントダウン)の表示

Last updated at Posted at 2017-10-18

javascriptで今年の残り日時(カウントダウン)の表示を行なう

javascriptのお勉強に今年の残り日時(カウントダウン)を作ったときのメモ

実装コード

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>カウントダウン</title>
</head>
<body>
  <h1 id="days" style="text-align:center;"></h1>
  <script>
  function time () {
    const now = new Date()
    // 来年の1月1日
    const firstDay = new Date(now.getFullYear() + 1, 0, 1)
    // 秒数差
    const diff = (firstDay.getTime() - now.getTime()) / 1000
    // 日時の計算と端数切り捨て
    const daysLeft = Math.floor(diff / (24 * 60 * 60))
    const hoursLeft = (Math.floor(diff / (60 * 60))) % 24
    let minitesLeft = (Math.floor(diff / 60)) % 60
    let secondsLeft = Math.floor(diff) % 60
    // 二桁表示
    minitesLeft = ('0' + minitesLeft).slice(-2)
    secondsLeft = ('0' + secondsLeft).slice(-2)
    // 出力
    document.getElementById('days').innerHTML = ('今年の残り時間は' + daysLeft + '' + hoursLeft + '時間' + minitesLeft + '' + secondsLeft + '秒です')
  }
  time()
  setInterval('time()', 500)
  </script>
</body>
</html>

こんな感じになる。
dateCount.gif

メモ

setInterval('time()',500);

1秒ごとの表示だと二桁表示の処理のせいか、たまに1秒スキップされてしまうので、0.5秒ごとの表示にしている。

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8