博客 / 詳情

返回

Vue中使用dayjs

安裝

cnpm i dayjs -S

全局安裝

import dayjs from "dayjs"
Vue.prototype.$dayjs = dayjs;//可以全局使用dayjs

使用

<div id="app">
  {{xx}}
</div>

<script>
    export default {
        data() { ... },
        computed: {
            xx() {
                return this.$dayjs().format("YYYY年MM月DD HH:mm:ss")
            }
        }
    }
</script>
當前時間
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())

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.