第一种:获取当前月 当前周 的第一天 时分秒都为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
}
使用Date对象可以获取时间相关的信息。获取当前时间:
var date = new Date()
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
alert(year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second)
获取一星期前的时间:
var now = new Date()
var date = new Date(now.getTime() - 7 * 24 * 3600 * 1000)
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
alert(year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second)
function getMonthWeek (a, b, c) {var date = new Date(a, parseInt(b) - 1, c), w = date.getDay(), d = date.getDate()
return Math.ceil(
(d + 6 - w) / 7
)
}
var today=new Date()
var last=new Date(today.getFullYear(), today.getMonth()+1,0)//获取当前月最后一天时间
var y = last.getYear()
var m = last.getMonth()+1
var d = last.getDate()
document.write( "当月最多有 ", getMonthWeek(y, m, d), " 周" )