首页 > 编程知识 正文

datetime转换为年月日格式,时间格式年月日时分秒转换文本格式

时间:2023-05-06 16:20:40 阅读:198367 作者:96

一句代码获取年月日格式的时间 let YMD= new Date().toLocaleDateString()console.log(YMD) // 2019/10/12 new Date()后转换的当前时间:结果如: 2019-10-12 15:19:28 // new Date() 获取当前标准时间,转为:YYYY-MM-DD h:m:s (年月日:时分秒) 格式getCurrentTime () { let date = new Date() let Y = date.getFullYear() let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1) let D = date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate() let hours = date.getHours() let minutes = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes() let seconds = date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds() date = Y + '-' + M + '-' + D + ' ' + hours + ':' + minutes + ':' + seconds console.log(date) // 2019-10-12 15:19:28 return date} 用dayjs 转换的当前时间:结果如:2019-10-12 15:19:28

安装 dayjs

npm install dayjs --save 或者 yarn add dayjs

引入dayjs

在单文件中直接用import引入它: import dayjs from 'dayjs'

或者

新建一个js文件(文件名可以随意取),如:dayjs.js,在该js文件中引入dayjs,并导出 var dayjs = require(‘dayjs’); export default dayjs; 在需要用到dayjs的文件中引入你创建的dayjs.js文件 import dayjs from '@/plugins/dayjs.js' 这里我创建的dayjs.js文件是放在vue项目下src目录下的plugins的,在文件中使用dayjs: // 用dayjs将获取的当前时间转为年月日时分秒的格式getDayjsTime () { let dayjsTime = dayjs(`${new Date()}`).format('YYYY-MM-DD HH:mm:ss') console.log(dayjsTime) // 2019-10-12 15:19:28 return dayjsTime} dayjs计算两个时间相差的天数

dayjs获取的时间对象的diff方法, Math.abs() 表示 对时间差取绝对值

// 获取时间差,相差的天数getDiffTime () { const date1 = dayjs('2019-9-12') const date2 = dayjs('2019-10-12') let diffTime = Math.abs(date1.diff(date2, 'day'))// 获取两个时间对象相差的天数,取绝对值 console.log(diffTime) // 30 return diffTime}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。