js中 输出当前时间年月日,月 为什么要+1呢。

JavaScript010

js中 输出当前时间年月日,月 为什么要+1呢。,第1张

因为时间对象中,月份是从0-11代表的现实中的第1-12个月。

日是1-31与现实中的日相同。

年也相同。

所以

(new Date()).getMonth()+1

才是当前的月份。

用jQuery EasyUI的Calendar做了一个DEMO,功能可以实现点击任意年月日,计算出与当天的日期差。

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=UTF-8">

<title></title>

<!--

这里添加jquery.js及jquery.easyui.min.js的引用

及相应CSS

-->

</head>

<body>

<h2>Calendar</h2>

<div class="easyui-calendar" style="width:180pxheight:180px">

</div>

</body>

</html>

<script>

$(".easyui-calendar").calendar({

onSelect: function (date) {

var selectdate = new Date(date.format("yyyy/MM/dd"))//取选中的日期

var currentdate = new Date(new Date().format("yyyy/MM/dd"))//取当前日期

alert("距今天:" + parseInt(Math.abs((selectdate - currentdate) / 1000 / 60 / 60 / 24)) + "天")//计算并显示相差天数

}

})

//格式化日期时间

Date.prototype.format = function (format) {

var o = {

"M+": this.getMonth() + 1, //month

"d+": this.getDate(), //day

"h+": this.getHours(), //hour

"m+": this.getMinutes(), //minute

"s+": this.getSeconds(), //second

"q+": Math.floor((this.getMonth() + 3) / 3), //quarter

"S": this.getMilliseconds() //millisecond

}

if (/(y+)/.test(format)) format = format.replace(RegExp.$1,

(this.getFullYear() + "").substr(4 - RegExp.$1.length))

for (var k in o) if (new RegExp("(" + k + ")").test(format))

format = format.replace(RegExp.$1,

RegExp.$1.length == 1 ? o[k] :

("00" + o[k]).substr(("" + o[k]).length))

return format

}

</script>