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

时间:2022-07-26
本文章向大家介绍获取当前时间的标准时间,转换为年月日:时分秒的格式,以及dayjs的使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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

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

或者

  1. 新建一个js文件(文件名可以随意取),如:dayjs.js,在该js文件中引入dayjs,并导出
var dayjs = require(‘dayjs’); export default dayjs;
  1. 在需要用到dayjs的文件中引入你创建的dayjs.js文件
import dayjs from '@/plugins/dayjs.js'
  1. 这里我创建的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
}