主要目的:一个物品需要15天的倒计时,15天后自动收货;
思路:下单时间+15天的时间 - 当前时间 = 倒计时的时间 ;
首先将时间转换成时间戳,然后进行计算。下面是将时间转成时间戳的三种方式:
var times1 = Date.parse(new Date());//获取的时间戳是把毫秒改成000显示
var times2 = (new Date()).valueOf();//获取了当前毫秒的时间戳
var times3 = new Date().getTime();//获取了当前毫秒的时间戳
复制代码
times2和times3转换出来的时间戳是一样的;
2、把获取到的时间戳进行计算:
/**
* 时间戳格式化函数
* @createTime 起始的时间
* @day 要进行倒计时的天数
*/
function timer(createTime,day){
var data = (new Date(createTime).getTime()+(day*24*60*60*1000))-new Date().getTime();
if (data > 0){
var day = check(parseInt(data/1000/60/60/24,10));
var h = check(parseInt(data/1000/60/60%24,10));
var m = check(parseInt(data/1000/60%60,10));
var s = check(parseInt(data/1000%60,10));
function check(i) {
if(i<10){
i = '0'+i;
}
return i;
}
}
console.log("还剩"+day+"天"+h+"小时"+m+"分钟"+s+"秒结束")
}
setInterval(function(){
timer('2018-09-08 14:30:00',15)
},1000)
复制代码
3、结果如下:
之前有个错误的15天倒计时写法如下:
一直不能出来正确的倒计时,有没有哪位大神指导下是为什么。
var time = (new Date("2018-09-08 12:00:00").getTime()+(15*24*60*60*1000))-new Date().getTime();
var date = new Date(time);
var D = checkTiem(date.getDate());
var h = checkTiem(date.getHours());
var m = checkTiem(date.getMinutes());
var S = checkTiem(date.getSeconds());
fifTimer = "剩"+D+"天"+h+"小时"+m+"分"+S+"秒自动确认";
console.log(fifTimer);
function checkTiem(i) {
if(i<10){
i = '0'+i;
}
return i;
}
复制代码