Moment.js 筆記
本篇為 Moment.js 的筆記。Moment.js 是一個 JavaScript 的套件,用來方便的處理任何和日期及時間相關的事,例如格式化日期,比對、運算時間等等。
Format
根據官方文件 Parse/String
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.
Moment 會把輸入的 String 放到 ISO 8601 及 RFC 2822 裡看看是否符合其型態,最後才會丟到 JavaScript 的 new Date()
中。
例如 DD/MM/YYYY
的表示法就不在 ISO 8601 的定義中,如果也不在 RFC 2822 的定義中,那麼 Moment 就會丟出 warning
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info
ISO 8601
根據 Wiki - ISO 8601,此定義是國際標準化組織(ISO, International Organization for Standardization)所定義的日期和時間表示方法。
Moment 中的範例可參考 Parse/String 底下的 Supported ISO 8601 Strings。
例如在台灣常用的日月年 2013-02-08
, 2013-02
, 2013
,時間表示 2013-02-08 09:30:26
,都是 ISO 8601 所支持的。也就是說其它國家的日期表示法若有不同,會以我們所習慣的年月日的順序來 Parsing。其中分離日期的 separator 必須要是 -
。
RFC 2822
RFC 為 Request for Comments(請求意見稿,Wiki - RFC)的縮寫,由 IETF(Internet Engineering Task Force,網際網路工程任務組)發表的一系列備忘錄。
Moment 中的範例可參考 Parse/String 底下的 The RFC 2822 date time format。
例如 6 Mar 17 21:22 UT
,其中 UT 是 Universal Time 的意思,或是可寫 GMT, Greenwich Mean Time,兩者都是比較老式(obsolete,出自 RFC 2822 寫 time zone 的地方)的寫法,代表時區為 +0000
。
或是 Mon, 06 Mar 2017 21:22:23 +0000
這樣的格式,依序是星期幾、天、月、年等等,詳細格式從 Moment 文件節錄如下
1 | 0 Day of Week in three letters, followed by an optional comma. (optional) |
常用 Snippets
取得現在時間,並指定特定時區
直接使用 moment()
可以得到目前的時間,時區會依據呼叫的瀏覽器或是伺服器(e.g., 用 Node.js 來呼叫,就會抓取其執行的伺服器時間)而變化。
1 | moment(); |
使用 utcOffset 這個 function,可以指定現在的時區。以下面程式碼為例,我們想指定台北的時區,就在 offset 李加入 +08:00。
1 | moment().utcOffset('+08:00'); |
下面程式碼則為找出台北現在日期的範例。
1 | moment().utcOffset('+08:00').format('YYYY-MM-DD'); |
對日期運算
- 加法
moment().add(Number, String)
,對年月日years
,months
,days
等加一個數字 - 減法
moment().subtract(Number, String)
,用法同加法
範例如下
1 | moment().add(7, 'days'); // As same as moment().add(7, 'd'); |
比較日期
可參考 Moment.js - Query。
以下為比較的 functions,參數為 (Moment|String|Number|Date|Array, String)
,第一個 input 是要比較的目標、第二個為要比較什麼(選填),可填入 year month week isoWeek day hour minute second
。
- isBefore()
- isSame()
- isAfter()
- isSameOrBefore()
- isSameOrAfter()
等等其它 functions,使用範例如下
1 | moment('2010-10-20').isBefore('2010-10-21'); // true |