方法一
<script>
function DateDiff(end){
today = new Date();
end = new Date(end);
if(end > today){
days = parseInt(Math.abs(end - today) / 1000 / 60 / 60 / 24);
}else{
days = parseInt(Math.abs(end - today) / 1000 / 60 / 60 / 24); // 如果不限制对比时间和当前时间大小可以不用if
}
return days;
}
</script>
//输出1
<script>document.write(DateDiff('2006-02-23'));</script>
//输出2
<script>document.write(DateDiff('2016-02-23'));</script>
//输出N
...
方法二(很多年前了,好处是可以精确到小时,不过同一页面不能多次调用)
<script type="text/javascript">
Date.prototype.Diff=function(endTime,text){
text=text||'{d}天{h}小时';
if((endTime.getTime()-this.getTime())>0){
var b=endTime.getTime()-this.getTime(),c=[],tpl=['{d}','{h}','{m}','{s}'];
c=[Math.floor(b/86400000),Math.floor(b%86400000/3600000),Math.floor(b%86400000%3600000/60000),Math.round(b%86400000%3600000%60000/1000)];
if(c[2].toString().length==1){
c[2]='0'+c[2];
};
if(c[3].toString().length==1){
c[3]='0'+c[3];
};
for(var i=0;i<c.length;i++){
text=text.replace(tpl[i],c[i]);
};
return text;
}else{
return '已过期'}
};
function showtime(){
document.getElementById('showtime').innerHTML=new Date(Date.parse('2006/02/23 00:45:00')).Diff(new Date());
setTimeout(function(){
showtime()
},1000)
};
window.onload=function(){
showtime();
}
</script>
<span id="showtime"></span> //调用