获取当前时间的标准时间,转换为年月日,时分秒的格式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/ddx2019/article/details/102535557

一句代码获取年月日格式的时间

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
    }

用dayjs 转换的当前时间:结果如:2019-10-12 15:19:33

  1. 安装dayjs :
    npm install dayjs --save 或者 yarn add dayjs

  2. 引入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的)

  3. 在文件中使用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以及一些相关的技术博客。

猜你喜欢

转载自blog.csdn.net/ddx2019/article/details/102535557
今日推荐