Advertisement

js计算距离生日天数

阅读量:

实现一个效果,在页面上显示当前日期年月日(格式: 2023年07月04日),和 距离你过生日还有多长时间,精确到天、时、分、秒(注:生日倒计时要实时变化)

复制代码
 <!DOCTYPE html>

    
 <html>
    
   <head>
    
     <meta charset="UTF-8" />
    
     <title>距离生日还有多久</title>
    
   </head>
    
   <body>
    
     <h1>距离生日还有:</h1>
    
     <div id="countdown"></div>
    
  
    
     <script>
    
       // 获取当前时间
    
       const now = new Date();
    
       const year = now.getFullYear();
    
       const month = now.getMonth() + 1;
    
       const day = now.getDate();
    
       const today = year + "年" + month + "月" + day + "日";
    
       document.write("<h1>今天是:" + today + "</h1>");
    
  
    
       // 获取生日
    
       const birthday = new Date("2000-10-01");
    
  
    
       // 计算距离生日还有多长时间
    
       function getCountdown() {
    
     const now = new Date();
    
     const timeDiff = birthday.getTime() - now.getTime();
    
     if (timeDiff <= 0) {
    
       clearInterval(timer);
    
       document.getElementById("countdown").innerHTML = "生日快乐!";
    
       return;
    
     }
    
     const days = Math.floor(timeDiff / (24 * 60 * 60 * 1000));
    
     const hours = Math.floor((timeDiff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
    
     const minutes = Math.floor((timeDiff % (60 * 60 * 1000)) / (60 * 1000));
    
     const seconds = Math.floor((timeDiff % (60 * 1000)) / 1000);
    
  
    
     document.getElementById("countdown").innerHTML =
    
       days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";
    
       }
    
  
    
       // 更新倒计时
    
       const timer = setInterval(getCountdown, 1000);
    
     </script>
    
   </body>
    
 </html>
    
    
    
    
    代码解读

运行效果:

全部评论 (0)

还没有任何评论哟~