获取倒计时
//返回截止日期的倒计时
function countDown(endTime) {
let d, h, m, s, ms: any;
//1.获取现在的时间
var presentDate = new Date();
//2.获取时间戳
var funtureTime = new Date(endTime.replace(/-/g, '/')).getTime();
var presenTime = presentDate.getTime();
//3.获取剩余的时间戳
var allTime = funtureTime - presenTime;
//this.minSec=allTime;
//4.把毫秒转换为秒
var allSecond = allTime / 1000;
if (allTime >= 0) {
//获取剩余多少天
d = Math.floor(allSecond / (3600 * 24));
//获取剩余多少小时
h = this.size(Math.floor(allSecond / 3600 % 24));
//获取剩余多少分钟
m = this.size(Math.floor(allSecond / 60 % 60));
//获取剩余多少秒
s = this.size(Math.floor(allSecond % 60));
//获取剩余多少毫秒
ms = (Math.floor(allTime % 1000) + '').substring(0, 1);
}
return allTime + 'T' + d + '天 ' + h + ':' + m + ':' + s + ' ' + ms
}
function size(num) {
return num < 10 && num >= 0 ? '0' + num : num;
}
//返回剩余时间的倒计时
function countDown(leftTime) { (例:leftTime->3200s)
let s, h, m: any;
s = (leftTime % 60) < 10 ? ('0' + leftTime % 60) : leftTime % 60;
h = leftTime / 3600 < 10 ? ('0' + parseInt((leftTime / 3600) + '')) : parseInt((leftTime / 3600) + '');
m = (leftTime - h * 3600) / 60 < 10 ? ('0' + parseInt(((leftTime - h * 3600) / 60) + '')) : parseInt(((leftTime - h * 3600) / 60) + '');
return h + ':' + m + ':' + s;
}
//多少时间之前
function formatTime(time) { //(time->日期)
if (arguments.length === 0) {
return null
}
let date
if (time === null || time === undefined) {
return null
}
if (typeof time === 'object') {
date = time
} else {
if (('' + time).length === 10) time = parseInt(time) * 1000
date = new Date(time)
}
// 修复Safari浏览器Invalid Date的问题
if (date.toString() === 'Invalid Date') {
const strArr = time.split(' ')
if (typeof time === 'string' && time.includes('-') && time.length > 10) {
const dateArr = strArr[0].split('-')
const timeArr = strArr[1].split(':')
date = new Date(dateArr[0], (dateArr[1] - 1), dateArr[2], timeArr[0], timeArr[1], timeArr[2])
} else {
const dateArr = strArr[0].split('-')
date = new Date(dateArr[0], (dateArr[1] - 1), dateArr[2])
}
}
const now = Date.now()
const diff = (now - date) / 1000
if (diff < 30) {
return '刚刚'
} else if (diff < 3600) { // less 1 hour
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return '1天前'
} else {
return '2天前'
}
}