首页 > 代码库 > javascript的时间段选择

javascript的时间段选择

最近要在页面上加一个时间段的选择控件,便上网搜寻一番,但找到的答案大都没有考虑时间段跨年的情况,所以做了些修改

本周的开始和结束日期

?
1
2
3
4
5
6
7
8
9
//当前日期
var now = new Date();
//今天是一周的第几天
var nowDayForWeek = now.getDay() === 0 ? 7 : now.getDay();
var oneDay = 1000 * 60 * 60 * 24;
//本周开始日期
var weekStartDay = new Date(now.getTime() - oneDay * (nowDayForWeek - 1));
//本周结束日期(本周开始日期 + 6天)
var weekEndDay = new Date(now.getTime() - oneDay * (nowDayForWeek - 7));
上周的开始和结束日期
?
1
2
3
4
//上周开始日期(当前日期 - 7天 - 今天是一周的第几天)
var lastWeekStartDay = new Date(now.getTime() - oneDay * (nowDayForWeek + 6));
//上周结束日期(当前日期 - 今天是一周的第几天)
var weekEndDay = new Date(now.getTime() - oneDay * (nowDayForWeek - 7));
本月的开始和结束日期(不存在跨年)
?
1
2
3
4
5
6
7
8
9
10
11
12
var nowMonth = now.getMonth();
var nowYear = now.getFullYear();
function getMonthDays (year, month){
   var monthStartDay = new Date(year, month, 1);
   var monthEndDate = new Date(year, month + 1, 1);
   var days = (monthStartDay - monthEndDate) / oneDay;
   return days;
}
//本月开始日期
var monthStartDay = new Date(nowYear ,nowMonth ,1);
//本月结束日期
var monthEndDay = new Date(nowYear ,nowMonth ,getMonthDays(nowYear ,nowMonth));
上月的开始和结束日期(存在跨年的可能)
?
1
2
3
4
5
6
var lastMonth = (nowMonth - 1) === -1 ? 11 : (nowMonth -1);
var lastMonthYear = lastMonth === 11 ? (nowYear -1) : nowYear;
//上月开始日期
var lastMonthStartDay = new Date(lastMonthYear ,lastMonth ,1);
//上月结束日期
var lastMonthEndDay = new Date(lastMonthYear ,lastMonth ,getMonthDays(lastMonthYear ,lastMonth));
本季度的开始和结束日期(不存在跨年)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function getQuarterStartMonth (month){
   var quarterStartMonth = 0;
   if(month < 3){
      quarterStartMonth = 0;
   }
   if(2 < month && month < 6){
      quarterStartMonth = 3;
   }
   if(5 < month && month < 9){
      quarterStartMonth = 6;
   }
   if(8 < month){
      quarterStartMonth = 9;
   }
   return quarterStartMonth;
}
//本季度开始日期
var quarterStartday= new Date(nowYear ,getQuarterStartMonth(nowMonth),1);
//本季度结束日期
var quarterEndday= new Date(nowYear ,getQuarterStartMonth(nowMonth) + 2 ,getMonthDays(nowYear ,getQuarterStartMonth(nowMonth) + 2));
上季度的开始和结束日期(存在跨年)
?
1
2
3
4
5
6
var lastQuarterMonth = (getQuarterStartMonth(nowMonth) - 3) < 0 ? 9 : getQuarterStartMonth(nowMonth - 3);
var lastQuarterYear = lastQuarterMonth === 9 ? nowYear - 1 : nowYear;
//上季度开始日期
var lastQuarterStartday = new Date(lastQuarterYear ,lastQuarterMonth ,1);
//上季度结束日期
var lastQuarterEndday = new Date(lastQuarterYear ,lastQuarterMonth + 2 ,getMonthDays(lastQuarterYear ,lastQuarterMonth + 2);