js 获取当前月和当前周的第一天和最后一天

如题所述

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

第一种:获取当前月 当前周 的第一天 时分秒都为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;
}
温馨提示:答案为网友推荐,仅供参考