今天偶然看到一個關於日期很方便的使用方法Day.js
下面說一下具體的使用方法:
github下載地址:https://github.com/iamkun/dayjs
也可以使用npm安裝:
npm install dayjs --save
然后在文件中引入:
import dayjs from 'dayjs'
// 或者 CommonJS
// var dayjs = require('dayjs');
dayjs().format();
如果不想安裝,還可以直接在script標簽中引入:
<!-- 最新的壓縮后的 JavaScript 文件 -->
<script src="https://unpkg.com/dayjs"></script>
<script> dayjs().format(); </script>
下面是API文檔地址:
https://github.com/iamkun/dayjs/blob/master/docs/zh-cn/API-reference.md
API參考:
- 當前時間 dayjs()
- 時間字符串 dayjs('2018-06-03')
- 時間戳 dayjs(1528361259484)
- Date 對象 dayjs(new Date(2018,8,18))
- 復制 dayjs().clone()
- 檢測當前 Dayjs 對象是否是一個有效的時間 dayjs().isValid()
- 獲取
年 : dayjs().year()
月 : dayjs().month()
日 : dayjs().date()
星期 : dayjs().day()
時 : dayjs().hour()
分 : dayjs().minute()
秒 : dayjs().second()
毫秒 : dayjs().millisecond() - 設置 dayjs().set('year',2017) dayjs().set('month',9)
- 增加時間並返回一個新的 Dayjs() 對象 dayjs().add(7, 'day') dayjs().add(7, 'year')
- 減少時間並返回一個新的 Dayjs() 對象 dayjs().subtract(7, 'year') dayjs().subtract(7, 'month')
- 返回當前時間的開頭時間的 Dayjs() 對象,如月份的第一天。 dayjs().startOf('year') dayjs().startOf('month')
- 返回當前時間的末尾時間的 Dayjs() 對象,如月份的最后一天。 dayjs().endOf('month') dayjs().endOf('year')
- 格式化 dayjs().format() dayjs().format('YYYY-MM-DD dddd HH:mm:ss.SSS A')
- 時間差 dayjs('2018-06-08').diff(dayjs('2017-06-01'),'years') dayjs('2018-06-08').diff(dayjs('2017-06-01'),'day') dayjs('2018-06-08').diff(dayjs('2017-06-01'),'hour')
- Unix 時間戳 (毫秒) dayjs().valueOf()
- Unix 時間戳 (秒) dayjs().unix()
- 返回月份的天數 dayjs().daysInMonth()
- 返回原生的 Date 對象 dayjs().toDate()
- 返回包含時間數值的數組 dayjs().toArray()
- 當序列化 Dayjs 對象時,會返回 ISO8601 格式的字符串 dayjs().toJSON() //2018-06-08T02:44:30.599Z
- 返回 ISO8601 格式的字符串 dayjs().toISOString() //2018-06-08T02:46:06.554Z
- 返回包含時間數值的對象 dayjs().toObject()
- 字符串 dayjs().toString()
- 檢查一個 Dayjs 對象是否在另一個 Dayjs 對象時間之前 dayjs('2018-06-01').isBefore(dayjs('2018-06-02'))
- 檢查一個 Dayjs 對象是否和另一個 Dayjs 對象時間相同 dayjs().isSame(dayjs())
- 檢查一個 Dayjs 對象是否在另一個 Dayjs 對象時間之后 dayjs().isAfter(dayjs())
Format | Output | Description |
---|---|---|
YY | 18 | 兩位數的年份 |
YYYY | 2018 | 四位數的年份 |
M | 1-12 | 月份,從 1 開始 |
MM | 01-12 | 月份,兩位數 |
MMM | Jan-Dec | 簡寫的月份名稱 |
MMMM | January-December | 完整的月份名稱 |
D | 1-31 | 月份里的一天 |
DD | 01-31 | 月份里的一天,兩位數 |
d | 0-6 | 一周中的一天,星期天是 0 |
dd | Su-Sa | 最簡寫的一周中一天的名稱 |
ddd | Sun-Sat | 簡寫的一周中一天的名稱 |
dddd | Sunday-Saturday | 一周中一天的名稱 |
H | 0-23 | 小時 |
HH | 00-23 | 小時,兩位數 |
m | 0-59 | 分鍾 |
mm | 00-59 | 分鍾,兩位數 |
s | 0-59 | 秒 |
ss | 00-59 | 秒 兩位數 |
SSS | 000-999 | 秒 三位數 |
Z | +5:00 | UTC 的偏移量 |
ZZ | +0500 | UTC 的偏移量,數字前面加上 0 |
A | AM | PM |
a | am | pm |