<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input id="y" type="text" placeholder="年" /> <input id="m" type="text" placeholder="月" />
<nput id="d" type="text" placeholder="日" /> <br /> <input type="button" id="btn" value="计算星期几" /> <input type="text"
id="w" placeholder="星期几">
<script>
var y = document.getElementById('y')
var m = document.getElementById('m')
var d = document.getElementById('d')
var w = document.getElementById('w')
var btn = document.getElementById('btn')
btn.onclick = function () {
var a = ''
a = y.value + '/' + m.value + '/' + d.value
var date = new Date(a)
var week = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
w.value = week[date.getDay()]
}
</script>
</body>
</script>
</body>
</html>
前言:需求里面有,做了就记录一下
第一种:获取当前月 当前周 的第一天 时分秒都为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
}