获取当前时间的标准时间,转换为年月日,时分秒的格式;以及dayjs的应用

获取当前时间的标准时间,转换为年月日,时分秒的格式;以及dayjs的应用

获取年月日时分秒的时间格式 计算时间差 使用dayjs如何计算时间差 获取当前年月日 取绝对值
版权


一句代码获取年月日格式的时间
let YMD= new Date().toLocaleDateString()
console.log(YMD) //  2019/10/12

new Date()后转换的当前时间:结果如: 2019-10-12 15:19:33
 // 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:33
      return date
    }
    
// **新写法:** 给 slice() 传入负值索引 ( 2021.3.25更新 博客内容 )

    getCurrentTime() {
      let date = new Date();
      let Y = date.getFullYear();
      let M = this.getStr(date.getMonth() + 1);
      let D = this.getStr(date.getDate());
      let hours = date.getHours();
      let minutes = this.getStr(date.getMinutes());
      let seconds = this.getStr(date.getSeconds());
      date =Y + "-" + M + "-" + D + " " + hours + ":" + minutes + ":" + seconds;
      console.log(date); //2019-10-12 15:19:33
      return date;
    },
    getStr(point) {
      return ("00" + point).slice(-2); // 从字符串的倒数第二个字符开始截取,一直截取到最后一个字符;(在这里永远截取该字符串的最后两个字符)
    },

用dayjs 转换的当前时间:结果如:2019-10-12 15:19:33
安装**dayjs** :
  npm install dayjs  --save  或者 yarn add dayjs 
1
引入**dayjs**:
1). 在单文件中直接用import引入它: import dayjs from 'dayjs'
或者
2). 新建一个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(currTime) // 2019-10-12 15:19:33
      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
}

关于dayjs,具体可参考 https://github.com/iamkun/dayjs以及一些相关的技术博客。
————————————————
版权声明:本文为CSDN博主「ddx2019」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ddx2019/article/details/102535557

 

posted @ 2021-10-21 14:34  前端白雪  阅读(2152)  评论(0编辑  收藏  举报