【时间Date转时间戳】
const d = Date.now()
// 结果:1625573962353
const d1 = (new Date()).valueOf();
// 结果:1625573962353,通过valueOf()函数返回指定对象的原始值获得准确的时间戳值;
const d2 = new Date().getTime();
// 结果:1625573962353,通过原型方法直接获得当前时间的毫秒值;
const d3 = Number(new Date()) ;
//结果:1625573962353,将时间转化为一个number类型的数值,即时间戳;
【时间戳转时间Date】
let date = new Date(1625573962353);
// Tue Jul 06 2021 20:19:22 GMT+0800 (中国标准时间)
【改造前:计算时间差示例】
watch: {
startTime (newValue, oldValue) {
const d = Date.now()
if (newValue > d) {
this.$message.warning('选中时间不得大于当前时间')
this.startTime = undefined // newValue = undefined似乎不管用
}
const diff = (this.endTime - newValue) / 1000 / 60
if (diff < 0) {
this.$message.warning('结束时间需大于开始时间')
this.startTime = undefined
} else if (diff > 30) {
this.$message.warning('时间差需小于30分钟')
this.startTime = undefined
}
}
}
由于业务需要时间控件[时分秒] 和日期控件[年月日] 要分开使用,且不可选择将来的时间
但是使用AntDesign时间日期控件时,日期控件 和 时间控件 打印出来的数值均带有年月日时间,所以不能直接用于比较大小
【改造后:计算时间差示例】
watch: {
startTime (newValue, oldValue) {
const d = Date.now()
const nowDate = moment().format('yyyy-MM-DD')
if (newValue > d && this.dateValue >= nowDate) {
this.$message.warning('选中时间不得大于当前时间')
this.startTime = undefined
}
const diff = (this.endTime - newValue) / 1000 / 60
if (diff < 0) {
this.$message.warning('结束时间需大于开始时间')
this.startTime = undefined
} else if (diff > 30) {
this.$message.warning('时间差需小于30分钟')
this.startTime = undefined
}
}
}
【自己动手获取年月日】
// 返回当前日期yyyy-MM-DD格式
nowDate () {
var date = new Date()
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
var nowDate = year + '-' + month + '-' + day
},
【时间格式化】
// moment为常用时间处理插件,官网:http://momentjs.cn/
const nowDate = moment().format('yyyy-MM-DD') // 当前时间格式化
const fdate = moment(date).format('yyyy-MM-DD') // 指定date格式化