一、dayjs是什么?
Day.js 是一个轻量的处理时间和日期的 JavaScript 库,和 Moment.js 的 API 设计保持完全一样。
Day.js 是更现代并且更轻量化,更加容易扩展的一个库。
二、使用步骤
1.安装使用
npm install dayjs --save
2.vue页面引入
import dayjs from 'dayjs' // 6.9k (gzip : 3k)
3.常用 api
说明 | 示例 | 结果 |
---|---|---|
获取当前 时间 | dayjs().format(‘YYYY-MM-DD HH:mm:ss’) | 2022-03-28 17:14:09 |
格式化传入的标准时间 | let time = Wed Apr 06 2022 16:34:24 GMT+0800 (中国标准时间) dayjs(time).format(‘YYYY-MM-DD HH:mm:ss’) | 2022-03-28 17:14:09 |
获取时间相隔 | dayjs(new Date(2021, 10, 1)).diff(new Date(2022, 10, 1), “day”) | -365 |
添加日、月、年、时、分、秒 | dayjs(“2022-09-17 08:10:00”).add(20, “minute”).format(‘YYYY-MM-DD HH:mm:ss’) | 2022-09-17 08:30:00 |
减去日、月、年、时、分、秒 | dayjs(“2022-09-17 08:10:00”).subtract(20, “minute”).format(‘YYYY-MM-DD HH:mm:ss’) | 2022-09-17 07:50:00 |
获取指定时间到现在 的时 间差 | import relativeTime from “dayjs/plugin/relativeTime” dayjs.extend(relativeTime) dayjs(“2021-09-16 13:28:55”).fromNow(); | a year ago |
获取时间相隔 | import weekOfYear from “dayjs/plugin/weekOfYear”; dayjs.extend(weekOfYear); dayjs(“2022-02-13 14:00:00”).week(); | 8 |
4.更多 api ➡️ 💙
点击👍dayjs中文文档
5.自定义格式化
// 格式化时间
Vue.prototype.$simpleTime = function(originVal) {
if (originVal) {
const dt = new Date(originVal);
const y = dt.getFullYear();
const m = (dt.getMonth() + 1 + '').padStart(2, '0');
const d = (dt.getDate() + '').padStart(2, '0');
const hh = (dt.getHours() + '').padStart(2, '0');
const mm = (dt.getMinutes() + '').padStart(2, '0');
const ss = (dt.getSeconds() + '').padStart(2, '0');
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
}
return ''
});
//传入标准时间
this.$simpleTime(new Date); //'2022-05-23 13:55:09'