js获取本周、上星期的开始结束时间
这两天在做一个报表体统,其中涉及到了一个根据本周,上周,本月,上月的时间来进行查询的问题,在这个我就教一下大家怎么实现,大家如果有更好的实现方法的,我也希望大家能说出来,我们交流交流.
首先呢,我写了一个方法,能实现获取本周,上周的开始时间,并且解决了跨年的问题
在这里先说明一下,月份,周几都是从0开始的这一点是需要我们注意的.
本周,上周的开始结束时间
function getTime(n){
var now=new Date();
var year=now.getFullYear();
//因为月份是从0开始的,所以获取这个月的月份数要加1才行
var month=now.getMonth()+1;
var date=now.getDate();
var day=now.getDay();
console.log(date);
//判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
if(day!==0){
n=n+(day-1);
}
else{
n=n+day;
}
if(day){
//这个判断是为了解决跨年的问题
if(month>1){
month=month;
}
//这个判断是为了解决跨年的问题,月份是从0开始的
else{
year=year-1;
month=12;
}
}
now.setDate(now.getDate()-n);
year=now.getFullYear();
month=now.getMonth()+1;
date=now.getDate();
console.log(n);
s=year+"年"+(month<10?('0'+month):month)+"月"+(date<10?('0'+date):date)+"日";
return s;
}
/***参数都是以周一为基准的***/
//上周的开始时间
console.log(getTime(7));
//上周的结束时间
console.log(getTime(1));
//本周的开始时间
console.log(getTime(0));
//本周的结束时间
console.log(getTime(-6));
上个月的结束时间
判断上个月一共有多少天的话,还得考虑一个问题,那就是2月份的时候,今年是闰年还是非闰年
思路: 1.先获取这个月的时间包括年月日
2.把每个月的天数列举出来,存到json对象中
3.遍历json对象,判断今年是否是闰年,如果是的话,那么他的2月份天数要加1
4.如果不是闰年的话,就匹配到这个月对应到的天数,赋值给totalDay
function getLastMonth() { var now = new Date(); var year = now.getFullYear(); //因为月份是从0开始的,所以获取这个月的月份数要加1才行 var month = now.getMonth() + 1; var date = now.getDate(); //这里设置的是上一个月,你也可以改为后面的几个月,就是加,但是要控制lastMonth的值不能大于12 var lastMonth = month-1; var totalDay = 0; var json = { 1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 }; for(var k in json) { if(year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) { if(lastMonth==2&&lastMonth==k){ totalDay=json[k]+1; } else if(lastMonth==k){ totalDay=json[k]; } } else{ if(lastMonth==k){ totalDay=json[k]; } } } return s="上个月的最后一天为为:"+year+"年"+(lastMonth<10?"0"+lastMonth:lastMonth)+"月"+totalDay+"日"; }