获取本周、本月、本季度的时间,可根据需要选择返回的时间的格式为时间戳或格式化时间或带时分秒的时间,也可选择结束时间为当前时间或者所选阶段内的结束时间

<script type="text/javascript">

getStartEnd(new Date(),'2',true,true,true) //截止当前时间(年-月-日)
getStartEnd(new Date(),'2',true,false) //截止当前阶段内结束时间(年-月-日)
getStartEnd(new Date(),'2',false,true) //截止当前时间(时间戳)
getStartEnd(new Date(),'2',false,false) //截止当前阶段内结束时间(时间戳)
/**a 当前时间对象,

b 0:本周、1:本月、2:本季度;
c true 返回起止时间标准格式 false 返回时时间戳
d true 截止当前时间 false 截止当前阶段结束时间
e 格式后的时间是否拼接当天时分秒
*/
function getStartEnd(a,b,c,d,e){
let arr = [],//起止日期数组
stime,//开始时间
etime,//结束时间
second = 1000*60*60*24, //一天的毫秒数,使用毫秒计算值是考虑到跨月的情况
month = a.getMonth(),//当前月份 0~11
year = a.getFullYear();//当前年份
if(b=='0'){
let week = a.getDay(), //当前星期几
minusDay = week!=0?week-1:6, //需要减去的天数
nowtime = a.getTime(); //当前时间戳
stime = nowtime - (minusDay * second), //开始时间
etime = stime+ (6 * second); //结束时间
}else if(b=='1'){
stime = new Date(year,month,1).getTime();
if (month == 11) {
year++;
month = 0;
} else {
//否则只是月份增加,以便求的下一月的第一天
month++;

}
let nextMonthDayOne = new Date(year, month, 1);//下月的第一天
etime = nextMonthDayOne.getTime() - second;//当月的最后一天

}else if(b=='2'){
let s_month, e_month;
if (month < 3) {
s_month = '00-01';
e_month = '02-31';
} else if (month < 6) {
s_month = '03-01';
e_month = '05-30';
} else if (month < 9) {
s_month = '06-01';
e_month = '08-30';
} else {
s_month = '09-01';
e_month = '11-31';
}
stime = new Date(year,s_month.split('-')[0],s_month.split('-')[1]).getTime();
etime = new Date(year,e_month.split('-')[0],e_month.split('-')[1]).getTime();
}
if(c){
// 未判断之前时间是时间戳格式
stime = getFormatTime(new Date(stime));
etime = getFormatTime(new Date(etime)); //当前阶段结束时间
if(d){
etime = getFormatTime(a) //当前截止时间
}
}


if(e){
arr.push(stime+' 00:00:00')
arr.push(etime+' 23:59:59')
}else{
arr.push(stime)
arr.push(etime)
}

return arr;

}
// 时间格式转化 年-月-日)
function getFormatTime(nowDate) {
// console.log(nowDate)
// console.log(nowDate.getDate())
let year = nowDate.getFullYear();
let month = nowDate.getMonth() + 1;
let day = nowDate.getDate();
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
return `${year}-${month}-${day}`;
};
</script>

猜你喜欢

转载自www.cnblogs.com/smallswallows/p/9686299.html
今日推荐