<script type="text/javascript">
//月份,从0(1月)到11(12月),初始化时要-1
var old_date = new Date(2016, 5, 27, 0, 0, 0);
var clock;
$(function () {
load();
clock = self.setInterval(load, 1000);
})
function load() {
var time = getTime(old_date, new Date());
$(".year").html(time.year);
$(".month").html(time.month);
$(".day").html(time.day);
$(".hour").html(time.hour);
$(".minute").html(time.minute);
$(".second").html(time.second);
}
//获取两个时间的间隔
function getTime(startTime, endTime) {
//getMonth() 方法可返回表示月份的数字,返回值是 0-11 之间的一个整数,所以在输出时需要+1才能输出当前的月份
let endYear = endTime.getFullYear();
let endMonth = endTime.getMonth() + 1;
let endDay = endTime.getDate();
let endHour = endTime.getHours();
let endMinute = endTime.getMinutes();
let endSecond = endTime.getSeconds();
let startYear = startTime.getFullYear();
let startMonth = startTime.getMonth() + 1;
let startDay = startTime.getDate();
let startHour = startTime.getHours();
let startMinute = startTime.getMinutes();
let startSecond = startTime.getSeconds();
var time = {
year: endYear - startYear,
month: endMonth - startMonth,
day: endDay - startDay,
hour: endHour - startHour,
minute: endMinute - startMinute,
second: endSecond - startSecond
};
if (time.second < 0) {
time.second += 60;
time.minute--;
}
if (time.minute < 0) {
time.minute += 60;
time.hour--;
}
if (time.hour < 0) {
time.hour += 24;
time.day--;
}
if (time.day < 0) {
if (endMonth > 1) time.day += getDaysByYearAndMonth(endYear, endMonth - 1);
else time.day += 31;
time.month--;
}
if (time.month < 0) {
time.month += 12;
time.year--;
}
return time;
}
//获取某年某月的天数
function getDaysByYearAndMonth(y, m) {
if (m != 2) {
if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) return 31;
return 30;
}
return (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) ? 29 : 28;
}
//获取某年的天数
function getDaysByYear(y) {
return (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) ? 366 : 365;
}
</script>
显示效果: