封装time.js如下:
/*
var now = new Date(); //创建Date对象的语法
注释:Date 对象会自动把当前日期和时间保存为其初始值
//获取特定格式的时间
now.getFullYear() // 获取完整的年份 2019
now.getMonth() //获取当前月份(0-11,0代表1月)
now.getDate() //获取当前日(1-31)
now.getDay() //获取当前星期X(0-6,0代表星期天)
now.getTime() //获取当前时间(从1970.1.1开始的毫秒数)
now.getHours() //获取当前小时数(0-23)
now.getMinutes() //获取当前分钟数(0-59)
now.getSeconds() //获取当前秒数(0-59)
now.toLocaleDateString() //获取当前日期 "2019/1/21"
*/
function countdown() {
let _date = new Date();
// 获取当天的时间在这里插入代码片
// console.log(4,_date);
let _nowTime = _date.getTime();
// 获取当天星期几
let _week = _date.getDay(); //获取当前星期X(0-6,0代表星期天)
// 设置一天的时长
let _dayLongTime = 24 * 60 * 60 * 1000;
// 获取周六周日距离现在还有多少毫秒
let Sunday = _nowTime + (7 - _week) * _dayLongTime;
let Saturday = _nowTime + (6 - _week) * _dayLongTime;
// 将毫秒数转为date对象
Sunday = new Date(Sunday);
const Y = Sunday.getFullYear() + '-';
const M = (Sunday.getMonth() + 1 < 10 ? '0' + (Sunday.getMonth() + 1) : Sunday.getMonth() + 1) + '-';
const D = (Sunday.getDate() < 10 ? '0' + Sunday.getDate() : Sunday.getDate()) + ' ';
const dateString = Y + M + D + '08:00:00';
// 定义结束时间戳
const end = Date.parse(new Date (dateString));
// 定义当前时间戳
const now = Date.parse(new Date());
// 做判断当倒计时结束时都为0
if (now >= end) {
this.day = 0;
this.hr = 0;
this.min = 0;
this.sec = 0;
return;
}
// 用结束时间减去当前时间获得倒计时时间戳
const msec = end - now;
let day = parseInt(msec / 1000 / 60 / 60 / 24); //算出天数
let hr = parseInt((msec / 1000 / 60 / 60) % 24); //算出小时数
let min = parseInt((msec / 1000 / 60) % 60); //算出分钟数
let sec = parseInt((msec / 1000) % 60); //算出秒数
//给数据赋值
this.day = day;
this.hr = hr > 9 ? hr : "0" + hr;
this.min = min > 9 ? min : "0" + min;
this.sec = sec > 9 ? sec : "0" + sec;
//定义this指向
const that = this;
// 使用定时器 然后使用递归 让每一次函数能调用自己达到倒计时效果
setTimeout(function () {
that.countdown();
}, 1000);
}
export default countdown
导入以及引用demo如下:
<template>
<view>
测试一下这个 time.js是否能用 <br>
------------------------------------------<br>
周末:{{day}} 天 <br>
时分秒倒计时 距离周六的八点
{{day}}天{{hr}}小时{{min}}分钟{{sec}}秒
</view>
</template>
<script>
import countdown from '../../utils/time.js'
export default {
data() {
return {
countdown:countdown,
day:0,
hr:0,
min:0,
sec:0
}
},
mounted() {
this.countdown();
},
methods: {
}
}
</script>
<style>
</style>