时间处理Dayjs

1,320 阅读1分钟

简介

  • 安装
 npm install dayjs --save

常用的函数

解析特定格式的日期

import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat)

dayjs("12-25-1995", "MM-DD-YYYY")

取值/赋值

  • 默认dayjs()获取的是当前的时间,可以用toDate方法将dayjs格式改为Date对象
// dayjs.toDate()=new Date()
dayjs.toDate()
  • 获取年,设置年(年月日,时分秒都可用类似方法)
dayjs().year()
dayjs().year(2000)
dayjs('2021/11/20').year()
  • 获取季度,周年等(需要引入插件)
import quarterOfYear from 'dayjs/plugin/quarterOfYear';
dayjs.extend(quarterOfYear)

dayjs('2010-04-01').quarter() // 2
dayjs('2010-04-01').quarter(2)

操作

  • 加上(注意如果是day或者月需要特殊处理),减去
dayjs().add(7, 'day')
  • 开始时间,结束时间,设置当天凌晨
dayjs().startOf('year')
dayjs().endOf('month')
dayjs().startOf('date') // 设置当天凌晨

显示

  • 格式化,具体DD,MM,YYYY代表啥可以去官网看下
dayjs('2019-01-25').format('DD/MM/YYYY')
  • 获取两个时间之间的时间差,
    diff可传三个参数
    只传第一个参数出来的是时间戳差
    传第二个参数代表求的是月差日差还是啥差
    第三个参数可传可不传,传true代表加浮点数,比较精确
const date1 = dayjs('2019-01-25')
const date2 = dayjs('2018-06-05')

date1.diff(date2) // 20214000000 default milliseconds
date1.diff(date2,'month') // 7
date1.diff(date2, 'month', true) // 7.645161290322581

查询

  • 可查询是否为某个时间之前,之后,是否相同,是否是两个时间之间,是否为闰年等等