Day.js:是一个极简的JavaScript库,可以为现代浏览器解析、验证、操作和显示日期和时间。
目录
2、具体使用(这里以YYYY-MM-DD dddd hh:mm:ss格式举例)
效果
一、介绍
1、官网:Day.js中文网
Day.js中文网Day.js是一个极简的JavaScript库,可以为现代浏览器解析、验证、操作和显示日期和时间。https://dayjs.fenxianglu.cn/
2、官方文档 - 中文网:安装 | Day.js中文网
安装 | Day.js中文网Day.js是一个极简的JavaScript库,可以为现代浏览器解析、验证、操作和显示日期和时间。https://dayjs.fenxianglu.cn/category/
3、部分API及示例
二、准备工作
1、安装依赖包
# 选择一个你喜欢的包管理器
# npm
$ npm install dayjs
# cnpm
$ cnpm install dayjs -S
# yarn
$ yarn add dayjs
# pnpm
$ pnpm install dayjs
注:也可以通过浏览器的 script
标签导入 CDN 文件使用
2、示例版本
"dayjs": "^1.11.1",
三、使用步骤
1、在单页面引入 'dayjs'
import dayjs, { Dayjs } from 'dayjs';
2、具体使用(这里以YYYY-MM-DD dddd hh:mm:ss格式举例)
dayjs().format("YYYY-MM-DD dddd hh:mm:ss"); // 2023-09-04 星期一 02:19:30
四、完整示例
<template
<div>{{ nowTime }}</div>
</template>
<script lang="ts" setup>
import { ref, onBeforeUnmount } from 'vue';
import dayjs, { Dayjs } from 'dayjs';
const nowTime = ref('');
nowTimes();
onBeforeUnmount(() => {
if (dateTimer.value) clearInterval(dateTimer.value);
})
function nowTimes() {
nowTime.value = dayjs().format("YYYY-MM-DD dddd hh:mm:ss");
console.log(nowTime.value); // 2023-09-04 星期一 02:19:30
dateTimer.value = setInterval(nowTimes, 1000)
}
</script>
注:定时器需要在页面销毁前做处理,否则容易造成内存泄漏。本示例已做处理,可参考。