1. new Date()

不设参数,则获取当前时间; 设参数,则获取参数内时间

要创建日期对象,就使用 new 操作符来调用 Date 构造函数:

  1. let now = new Date();

2. 年,月,日,时,分,秒,毫秒

获取当前时间的年,月,日,时,分,秒,毫秒

  1. <!-- 获取当前的时间 -->
  2. <script>
  3. // Date
  4. var d = new Date();
  5. /* 年,月,日 */
  6. var year = d.getFullYear();
  7. var month = d.getMonth();
  8. var date = d.getDate();
  9. /* 时,分,秒,毫秒
  10. 1s =1000 millisecond
  11. */
  12. var hour = d.getHours();
  13. var minute = d.getMinutes()
  14. var second = d.getSeconds();
  15. var mills = d.getTime();
  16. console.log(d);//Tue Dec 01 2020 22:05:23 GMT+0800 (中国标准时间)
  17. console.log(year);
  18. console.log(month+1) //月份是从0开始的,要加1
  19. console.log(date)
  20. console.log(hour)
  21. console.log(minute)
  22. console.log(second);
  23. console.log(mills)
  24. </script>

3. 倒计时时钟

  1. <p id="app">
  2. 10:10:01
  3. </p>
  4. <script>
  5. function handleTime(value) {
  6. if (value < 10) {
  7. return "0" + value;
  8. }
  9. return value;
  10. }
  11. function showTime() {
  12. var app = document.getElementById("app")
  13. var endTime = "2020-12-02 00:00:00";
  14. /* 1.获取结束时间的毫秒 */;
  15. endTime = new Date(endTime).getTime();
  16. /* 2.获取当前时间的毫秒 */
  17. var nowTime = new Date().getTime();
  18. /* 3.获取他们之间的差 */
  19. var gapTime = endTime - nowTime;
  20. /* 4.将他们的差转换为时分秒 */
  21. var seconds = Math.floor(gapTime / 1000);
  22. var hours = handleTime(Math.floor(seconds / 3600));
  23. seconds = seconds % 3600;
  24. var minutes = handleTime(Math.floor(seconds / 60));
  25. seconds = handleTime(seconds % 60);
  26. var sum = hours + ":" + minutes + ":" + seconds;
  27. app.innerHTML = sum;
  28. setTimeout(function(){
  29. showTime()
  30. },1000)
  31. }
  32. showTime();
  33. </script>

或者

  1. showTime();
  2. setInterval(function(){
  3. showTime();
  4. },1000)

4.动态时钟

  1. <div id="app">
  2. <img src="images/0.png" alt="">
  3. <img src="images/0.png" alt="">
  4. <span>:</span>
  5. <img src="images/0.png" alt="">
  6. <img src="images/0.png" alt="">
  7. <span>:</span>
  8. <img src="images/0.png" alt="">
  9. <img src="images/0.png" alt="">
  10. </div>
  11. <script>
  12. function handleTime(value) {
  13. if (value < 10) {
  14. return "0" + value;
  15. }
  16. return ""+ value;
  17. }
  18. function showTime() {
  19. var imgs = document.querySelectorAll("#app img")
  20. var d = new Date();
  21. var hours = handleTime(d.getHours());
  22. var minutes = handleTime(d.getMinutes());
  23. var seconds = handleTime(d.getSeconds());
  24. var sum = hours + minutes + seconds;
  25. console.log(sum);
  26. for (var i = 0; i < imgs.length; i++) {
  27. console.log(sum[i])
  28. // imgs[i].src = "images/" + sum[i] + ".png";
  29. imgs[i].src = `images/${sum[i]}.png`;
  30. }
  31. setTimeout(function(){
  32. showTime()
  33. },1000)
  34. }
  35. showTime()
  36. </script>