Vue的实时时间转换Demo

时间:2022-09-16 23:07:16

Vue的实时时间转换Demo

time.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>时间转换指令</title>
</head>
<body> <div id="app" v-cloak>
<div v-time="timeNow"></div>
<div v-time="timeBefore"></div>
</div> <script src="../js/vue.js"></script>
<script src="./time.js"></script>
<script src="./index.js"></script>
</body>
</html>

index.js

var app = new Vue({
el:'#app',
data:{
timeNow:(new Date()).getTime(),
timeBefore:1488930695721
}
});

time.js

var time= {
//获取当前时间戳
getUnix: function () {
var data = new Date();
return data.getTime();
}, //获取今天0点0分0秒的时间戳
getTodayUnix: function () {
var data = new Date();
data.setHours(0);
data.setMinutes(0);
data.setSeconds(0);
data.setMilliseconds(0);
return data.getTime();
}, //获取今年1月1日0点0分0秒的时间戳
getYearUnix: function () {
var data = new Date();
data.setMonth(0);
data.setDate(1);
data.setHours(0);
data.setMinutes(0);
data.setSeconds(0);
data.setMilliseconds(0);//毫秒
return data.getTime();
},
//获取标准的年月日
getLastDate: function (time) {
var date = new Date(time);
var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
return date.getFullYear() + '-' + month + "-" + day; },
//转换时间
getFormatTime: function (timestamp) { var now = this.getUnix();
var today = this.getTodayUnix();
var year = this.getYearUnix();
var timer = (now - timestamp) / 1000;//把时间戳改为秒级
var tip = '';
if (timer <= 0) {
tip = '刚刚';
} else if (Math.floor(timer / 60) <= 0) {
tip = '刚刚';
} else if (timer < 3600) {
tip = Math.floor(timer / 60) + '分钟前';
} else if (timer >= 3600 && (timestamp - today >= 0)) {
tip = Math.floor(timer / 3600) + '小时前';
} else if (timer / 86400 <= 31) {
tip = Math.ceil(timer / 86400) + '天前';
} else {
tip = this.getLastDate(timestamp);
} return tip;
} } Vue.directive('time',{
bind:function (el,binding) {
el.innerHTML = time.getFormatTime(binding.value);
el._timeout_ = setInterval(function () {
el.innerHTML = time.getFormatTime(binding.value);
},60000);
},
unbind:function(el){
clearInterval(el._timeout_);
delete el._timeout_; } })