JS:如何计算一个月有多少天

JavaScript020

JS:如何计算一个月有多少天,第1张

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

前言:需求里面有,做了就记录一下

第一种:获取当前月 当前周 的第一天 时分秒都为0,最后一天时分秒为23:59:59

ps:如果想获得指定日期的当前周,new Date('2020-1-2') 传参就可以了

//获取当前周

getTime(){

var date = new Date()

// 本周一的日期

date.setDate(date.getDate() - date.getDay() + 1)

var begin = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00"

// 本周日的日期

date.setDate(date.getDate() + 6)

var end = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59"

let timeInfo={

begin:begin,

end:end

}

return timeInfo

}

//获取当前月

getMtime(){

var data=new Date()

data.setDate(1)

data.setHours(0)

data.setSeconds(0)

data.setMinutes(0)

var start = data.getTime()

var currentMonth = data.getMonth()

var nextMonth = ++currentMonth

var nextMonthFirstDay = new Date(

data.getFullYear(),

nextMonth,

1

)

var end = nextMonthFirstDay-1

let timeInfo={

begin: this.timestampToTime(start),//这里调用时间戳转年月日时分秒方法

end: this.timestampToTime(end)

}

return timeInfo

}

//时间戳转年月日时分秒方法

timestampToTime (cjsj) {

var date = new Date(cjsj) //时间戳为10位需*1000,时间戳为13位的话不需乘1000

var Y = date.getFullYear() + '-'

var M = (date.getMonth()+1 <10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'

var D = (date.getDate() <10 ? '0'+date.getDate() : date.getDate()) + ' '

var h = (date.getHours() <10 ? '0'+date.getHours() : date.getHours()) + ':'

var m = (date.getMinutes() <10 ? '0'+date.getMinutes() : date.getMinutes())+ ':'

var s = (date.getSeconds() <10 ? '0'+date.getSeconds() : date.getSeconds())

return Y+M+D+h+m+s

}

示例代码如下:

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