var target = document.getElementById('target');
function getTimeString(){ // 要计算任意两个日期的时间差只要修改currentDate和currentYearDate的值即可
var currentDate = new Date();
var year = currentDate.getFullYear();
var currentYearDate = new Date(year,11,30,23,59,59); //这里应该写11而不是12,因为Date.getDay()方法返回数值总是比当前月份小1
var time = (currentYearDate - currentDate) / 1000; //得到距今年底还有多少秒
var day = Math.floor(time / (24*60*60));
var hours = Math.floor(time % (24*60*60) / (60*60));
var minutes = Math.floor(time % (24*60*60) % (60*60) / 60);
var seconds = Math.floor(time % (24*60*60) % (60*60) % 60);
var str = year +"年还剩"+ day +"天"+ hours +"小时" + minutes +"分" + seconds +"秒";
target.innerHTML = str;
}
setInterval(getTimeString,1000);
下面这个方法也行,就是性能不太好
var target = document.getElementById('target');
function getTimeString(){
var date = new Date();
var eachMonthDay = [31,28,31,30,31,30,31,31,30,31,30,31];
if(date.getFullYear() % 4 == 0){
eachmonthDay[1] = 29;
}
var dateString = date.getFullYear() + "年还剩" + (11-date.getMonth()) + "月";
//计算还剩多少天,以当前月天数为基准
dateString += eachMonthDay[date.getMonth()] - date.getDate() + "天";
//计算还剩多少小时,以当天为基准
dateString += (24 - date.getHours() - 1) + "小时";
//计算还剩多少分钟,以当前时间为准
dateString += (60 - date.getMinutes() -1) + "分";
//计算还剩多少秒,以当前时间为准
dateString += (60 - date.getSeconds()) + "秒";
target.innerHTML = dateString;
}
var timer = setInterval(getTimeString,1000);