# Moment.js > 方便你操控各種時間毛病 可透過解析、轉換、設置、格式化日期的js函式庫,透過 moment.js 就可以簡化使用JavaScript 的時間處理,更快速的達到與時間相關的效果呈現。 [我是官網API](https://momentjs.com/) --- ### **Format Dates** moment().format("給予你想要顯示的時間格式") ``` moment().format('MMMM Do YYYY, h:mm:ss a'); // 三月 31日 2020, 3:04:13 下午 moment().format('dddd'); // 星期二 moment().format("MMM Do YY"); // 3月 31日 20 moment().format('YYYY [escaped] YYYY'); // 2020 escaped 2020 moment().format("hA"); // 5PM hA 表示AM和PM ``` 在運用時間表示中最常使用的 Timestamp(時間戳記),也可以用 X 來表示 ``` moment().format("X"); // 1541497385 ``` --- ### **運算** moment.js 可以運算時間,像是取出時間的最大值,或是增加天數。 ``` moment().add(7, 'days'); // 現在的日期加上七天 moment().add(7, 'days').add(1, 'months') // 再加上1個月 ``` --- ### **實際運用** 在專案中有設定固定的開放時間,此時moment.js 就能方便我做計算 ``` let now = moment(); //取得現在時間 let beforeTime = moment('4:04:00', 'hh:mm:ss'); let afterTime = moment('13:04:00', 'hh:mm:ss'); if (now.isBetween(beforeTime, afterTime)) { console.log('當前不在遊玩時間內') }; ``` 如果不在符合的時間調間內,算出距離開放時間的差距後重整頁面: ``` let nowTime: number = moment().valueOf();// 當今時間轉為毫秒數 let openingTime: number = moment('13:04:00', 'hh:mm:ss').valueOf(); let timeInterval: number = openingTime - nowTime; setTimeout(() => { window.location.reload() }, timeInterval); ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up