new Date()

MDN Web Docs

Date 物件是基於世界標準時間(UTC) 1970 年 1 月 1 日開始的毫秒數值來儲存時間。

語法

new Date()

獲取其他精細的時間

Date.prototype 方法

Date.prototype.getHours() // 回傳本地時間的小時(0-23) Date.prototype.getSeconds() // 回傳本地時間的秒數(0-59)

範例:利用 setInterval 跟時間結合,印出秒數

function setDate() { const now = new Date() const second = now.getSeconds() console.log(second) } setInterval(setDate, 1000)

範例:利用得到的秒數,結合時鐘秒針轉換成角度方式

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

html

<div class="clock"> <div class="clock-liner center"> <div class="clock-dot center"></div> <div class="hour-hand"></div> <div class="min-hand"></div> <div class="second-hand"></div> </div> </div>

js

const secondTime = document.querySelector('.second-hand') function setDate() { const now = new Date() const second = now.getSeconds() const secondDegree = ((second/60)*360 -90) // 計算((秒數 / 六十格)*360度) // 得到應該要的角度 // 但這邊的秒針因為定位起始要在12點鐘方向時, // 為 270 度,所以要 -90 才會將秒針放置在12 點鐘方向 secondTime.style.transform = `rotate(${secondDegree}deg)` console.log('second', second) } setInterval(setDate, 1000)
tags: JS

最後,親愛的大家!我需要你的大聲鼓勵 ٩(⚙ᴗ⚙)۶

如果覺得這篇文章對你有幫助,請給我個一個小小的鼓勵 ❤ 讓我知道,這會成為我寫下去很大的動力。
對了,我還有其他文章,如果有興趣也來逛逛吧!
(文章中如有覺得不妥之處、錯誤內容,也可以透過聯絡我,我會儘速改善,感謝!)

☞ YoJanni 珍妮 2021 正在設計轉職前端的路上,希望大家在學習的路上能夠一起成長
☞ 聯絡我