1.安装
Node.js 项目中使用 Day.js,只需使用 npm 安装
npm install dayjs
其它地方使用,参考中文文档
2.引入
import dayjs from 'dayjs'
3.使用
时间格式化
dayjs().format()
// 默认返回的是 ISO8601 格式字符串 '2020-04-02T08:02:17-05:00'
dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]')
// 'YYYYescape 2019-01-25T00:00:00-02:00Z'
dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'
我的使用
import dayjs from 'dayjs'
const getContent = ()=>{
setContent([
...contentList,
{
rpid: uuidv4(),
user: {
uid: '30009257',
avatar,
uname: '黑马前端',
},
content: areaValue,
ctime: dayjs(new Date()).format('MM-DD HH:mm'), //将当前时间格式化指定格式
like: 66,
},])
}
<script>
let time = new Date()
//1、格式化年份
console.log(dayjs(time).format('YYYY')) // 2023 (YYYY 四月份的年份,YY则是23)
//2、格式化月份
console.log(dayjs(time).format('MM')) // 01 (MM-两位数的月份)
//3、格式化 年-月-日
console.log(dayjs(time).format('YYYY-MM-DD')) // 2023-01-19
console.log(dayjs(time).format('YYYY年MM月DD日')) // 2023年01月19日
//4、格式化 年月日时分秒:YYYY-MM-DD HH:mm:ss
console.log(dayjs(time).format('YYYY-MM-DD HH:mm:ss')) // 2023-01-19 16:25:23
</script>