dayjs使用
安装
npm install dayjs --save
mport dayjs from 'dayjs'
dayjs().format()
使用
-
使用字符串拼接时,会触发隐式转换
‘*’+dayjs(date) //时间戳
当使用+运算符进行字符串拼接时,JavaScript会尝试将对象转换为原始值(Primitive Value)。Day.js对象在转换时会调用valueOf()方法,而Day.js的valueOf()默认返回的是时间戳(自1970年1月1日以来的毫秒数)
-
避免隐式转换
-
使用模板字符串
console.log(`*${dayjs(date)}`)
-
使用String函数
'*' + String(dayjs(date))
-
-
-
显式调用
console.log('*' + dayjs(date).format('YYYY-MM-DD HH:mm:ss'));
-
unix()方法
// dayjs.unix() 方法接受的参数是一个以秒为单位的时间戳 console.log(dayjs.unix(1318781876));
-
检测是否有效
// 检测当前 Dayjs 对象是否是一个有效的时间。 dayjs().isValid()
-
是否传参的区别
// dayjs().month() 方法如果不带参数调用,是获取当前日期对象的月份,返回值是从 0 开始计数(0 表示 1 月,1 表示 2 月,以此类推)。 // 当你传入参数调用,比如 dayjs().month(0) ,它是将日期对象的月份设置为 1 月 console.log(dayjs().month()); console.log(dayjs().month(0));
-
date()和set()使用
//在处理日期中 “日” 相关的频繁操作场景下,代码的可读性较高,也便于维护 console.log(dayjs().date(1)); // 在需要批量设置多个日期属性,或者动态根据变量来设置不同日期属性的场景下,set() 方法更具优势 console.log(dayjs().set('date',1));
-
valueOf()
// Day.js的valueOf()返回时间戳 console.log(dayjs(new Date()).valueOf());
-
toString()
// toString()默认返回ISO格式字符串 console.log(dayjs(date).toString());
-
add()
console.log(dayjs().add(7, 'day'));
-
substract()
console.log(dayjs().subtract(7, 'year'));
-
startOf()
//会返回本周日的开始时间,从w:0开始 console.log(dayjs().startOf('week'));
-
endOf()
// 获取当前时间所在月的最后时刻(月最后一天的23:59:59.999) console.log(dayjs().endOf('month'));
-
format
// 日期字符串并格式化 console.log(dayjs().format(''));