直接把代码拿到uniapp上运行
控制台打印
注意:在操作的时候可能会出现(无效的时间)
由于是ios不支持横杠(-) 2022-10-23 13:00:00,把(-)换成(/)就ok了
<template>
<view>
</view>
</template>
<script>
export default {
data() {
return {
time: '',
};
},
onLoad(options) {
this.time = this.getTime()
console.log(this.time)
this.getDateDiff(this.time)
},
methods: {
//获取当前时间
getTime: function() {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
month >= 1 && month <= 9 ? (month = "0" + month) : "";
day >= 0 && day <= 9 ? (day = "0" + day) : "";
var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
return timer;
},
getDateDiff(data) {
console.log('当前时间:'+data)
var time = this.getDays(new Date('2022-10-23 13:00:00'), new Date('2022-10-23 17:24:06 '));
},
getDays: function(date1, date2) {
console.log('date2:'+date2.getTime())
console.log('date1:'+date1.getTime())
console.log('时间差:'+(date2.getTime() - date1.getTime()))
//每一天的毫秒数
const dateTime = 1000 * 60 * 60 * 24;
//计算出两个日期的天数差
const dateDiff = Math.floor(((date2.getTime() - date1.getTime())));
console.log('dateDiff:'+dateDiff)
var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000))
var leave1 = dateDiff % (24 * 3600 * 1000)
console.log('leave1:'+leave1)
var hours = Math.floor(leave1 / (3600 * 1000))
console.log('相差小时数:' + hours)
//分钟数
var leave2 = leave1 % (3600 *1000)
var minutes = Math. floor(leave2 / (60 *1000))
console. log('相差分钟数:'+ minutes )
//秒
var leave3 = leave2 % (60 *1000)
var seconds = Math.round(leave3 / 1000)
console. log('相差秒数:'+seconds)
return dayDiff
},
}
}
</script>
<style lang="scss">
</style>