安装

npm i dayjs -S

使用

import dayjs from 'dayjs'

dayjs().format('YYYY-MM-DD HH:mm:ss')

API

获取当前时间

dayjs()
// 2020-12-31T15:00:00.000Z

格式化时间

dayjs().format('YYYY-MM-DD HH:mm:ss')
// 例子
const time = '2020-12-31T15:00:00.000Z'
const formatTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss')

获取时间戳

dayjs().valueOf()
// 例子
const time = '2020-12-31T15:00:00.000Z'
const timestamp = dayjs(time).valueOf()

获取年份

dayjs().year()

获取月份

dayjs().month()

获取日期

dayjs().date()

获取小时

dayjs().hour()

获取分钟

dayjs().minute()

获取秒

dayjs().second()

获取毫秒

dayjs().millisecond()

设置年份

dayjs().year(2020)
// 例子
const time = '2020-12-31T15:00:00.000Z'
const formatTime = dayjs(time).year(2021).format('YYYY-MM-DD HH:mm:ss')
// 输出 2021-12-31 15:00:00

设置月份

dayjs().month(11)

设置日期(月份最大天数)

dayjs().date(31)
// 例子
const time = '2020-12-31T15:00:00.000Z'
const formatTime = dayjs(time).date(30).format('YYYY-MM-DD HH:mm:ss')
// 输出 2020-12-30 15:00:00

设置小时

dayjs().hour(23)
Last Updated:
Contributors: 黄定鑫