js计算一个月多少天

JavaScript031

js计算一个月多少天,第1张

JavaScript获取每个月的天数,参数说明:month:月份year:年,函数被调用后,将直接返回:days天数。

view sourceprint?

01function getDaysInMonth(month,year){

02var days

03if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) days=31

04else if (month==4 || month==6 || month==9 || month==11) days=30

05else if (month==2) {

06if (isLeapYear(year)) { days=29}

07else { days=28}

08}

09return (days)

10}

function getCountDays() {

        var curDate = new Date()

        /* 获取当前月份 */

        var curMonth = curDate.getMonth()

       /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */

       curDate.setMonth(curMonth + 1)

       /* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */

       curDate.setDate(0)

       /* 返回当月的天数 */

       return curDate.getDate()

}

//例如,  获取当前月份(现在是3月)的总天数: 

getCountDays()       // 返回31

示例代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html charset=gb2312" />

<title>JS 获取当月天数</title>

<script  type="text/javascript" language="javascript">

function getDays(){

//构造当前日期对象

var date = new Date()

//获取年份

var year = date.getFullYear()

//获取当前月份

var mouth = date.getMonth() + 1

//定义当月的天数;

var days 

//当月份为二月时,根据闰年还是非闰年判断天数

if(mouth == 2){

        days= year % 4 == 0 ? 29 : 28

        

    }

    else if(mouth == 1 || mouth == 3 || mouth == 5 || mouth == 7 || mouth == 8 || mouth == 10 || mouth == 12){

        //月份为:1,3,5,7,8,10,12 时,为大月.则天数为31;

        days= 31

    }

    else{

        //其他月份,天数为:30.

        days= 30

        

    }

    

    //输出天数

    alert('当月天数为:'+days)

}

</script>

</head>

<body onload="getDays()">

</body>

</html>