js返回当前月份有多少天

JavaScript07

js返回当前月份有多少天,第1张

示例代码如下:

<!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>

<script>

document.writeln('练习6:<br>'+' 输入年份、月份,显示当月的天数'+'<br>')

var year= parseInt(prompt('练习6\n请输入一个年份'))

var month= parseInt(prompt('练习6\n请输入一个月份'))

document.writeln('您输入了'+year+'年'+'<br>')

document.writeln('您输入了'+month+'月'+'<br>')

switch(month)

{

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12:

document.writeln('您输入的'+month+'月'+'有31天')

break

case 4:

case 6:

case 9:

case 11:

document.writeln('您输入的'+month+'月'+'有30天')

break

case 2:

if(year%4===0&&year%100!==0||year%400===0)

{

document.writeln('您输入的'+month+'月'+'有29天')

}else

{

document.writeln('您输入的'+month+'月'+'有28天')

}

// (years%4===0&&years%100!==0||years%400===0)?

// document.writeln('本月有29天'):

// document.writeln('本月有28天')

break

ddefault :

document.writeln('亲,您的输入不正确'+'您输入的是'+month+'月')

break

}

</script>

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