日期: 2021/09/26 天气:阴
在说day.js之前,首先要提一个老大哥moment.js,老大哥可谓是处理时间的常青树,基本上之前的项目都是用这个来处理的,但是比较遗憾的是,现在不维护了,而且包体积太大,已经不适用于现在追求更小代码包体积的今天,day.js就是体积更小的时间处理神器,其实他的思想跟按需加载一样,用到哪个方法,再按需引入插件即可.
全局参数,time 就是传入的要格式化的时间,假如是2021年12月12日上午5点整
所有需要引入插件的都需要如下操作,比如要引入isLeapYear插件,就需要这样引入后才能操作
import * as dayjs from 'dayjs'
import * as isLeapYear from 'dayjs/plugin/isLeapYear' // import plugin
import 'dayjs/locale/zh-cn' // import locale
dayjs.extend(isLeapYear) // use plugin
dayjs.locale('zh-cn') // use locale
全局关于时间操作的值
单位 | 缩写 | 描述 |
---|---|---|
week | w | 周 |
day | d | 星期(星期日0,星期六6) |
month | M | 月份(0-11) |
quarter | Q | 依赖QuarterOfYear插件 |
year | y | 年 |
hour | h | 小时 |
minute | m | 分钟 |
second | s | 秒 |
millisecond | ms | 毫秒 |
转化当前时间/自定义时间为年月日时分秒
dayjs().format('YYYY-MM-DD') // 2021-09-26
dayjs(time).format('YYYY-MM-DD') // 2021-12-12
dayjs().format('YYYY-MM-DD HH:mm:ss') // 2021-09-26 10:00:00
dayjs(time).format('YYYY-MM-DD HH:mm:ss') // 2021-12-12 05:00:00
获取当前时间/自定义时间的开始时间、结束时间的时间戳
const start_time = dayjs(((dayjs(date).startOf('day')).$d)).valueOf();
const end_time = dayjs(((dayjs(date).endOf('day')).$d)).valueOf();
return { start_time, end_time }
获取当前时间/自定义时间当天某时刻的时间戳
return dayjs(time).set('hour', hour).set('minute', minute).set('second', second).set('millisecond', millisecond).valueOf()
获取距离当前时间/自定义时间相差某些时间的时间戳
dayjs().add(1, 'day') // 当前时间加1天
dayjs().subtract(1, 'day') // 当前时间减去1天
获取开始时间
dayjs().startOf('year') //当前时间开始年时间
获取结束时间
dayjs().endOf('year') // 当前时间结束年时间
获取当前时间/自定义时间周日期
const dayjs = require("dayjs");
const isoWeek = require('dayjs/plugin/isoWeek')
dayjs.extend(isoWeek);
dayjs(time).isoWeekday(); //7
获取某段时间内的时间段列表
formatEveryDay: (start, end) => {
let dateList = [];
const startTime = getDate(start);
const endTime = getDate(end);
while ((endTime.getTime() - startTime.getTime()) >= 0) {
const year = startTime.getFullYear();
const month = startTime.getMonth() + 1 < 10 ? '0' + (startTime.getMonth() + 1) : startTime.getMonth() + 1;
const day = startTime.getDate().toString().length == 1 ? "0" + startTime.getDate() : startTime.getDate();
const formatDay = `${year}-${month}-${day}`;
dateList.push(formatDay);
startTime.setDate(startTime.getDate() + 1);
}
return dateList;
},
const getDate = (datestr) => {
const temp = datestr.split("-");
const date = new Date(temp[0], temp[1] - 1, temp[2]);
return date;
}
//入参两段时间的时间,比如start:2021-09-23,end:2021-09-26,返回值['2021-09-23', '2021-09-24','2021-09-25','2021-09-26']