JS获取今日、本周、本月、本年的时间范围

代码
kssj表示过去某天的时间
jssj表示今天的时间
new Date为今天的时间
getThisWeekFirstDay 函数获取这一周第一天的时间
getThisMonthFirstDay 函数获取这一个月第一天的时间
getThisYearFirstDay 函数获取这一年第一天的时间
最后的Date类型转换是为了格式化时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" id="dateFrom" value="">
<input type="text" id="dateTo" value="">
<script>
window.onload = function() {
// getDate("thisDay");
// getDate("thisWeek");
// getDate("thisMonth");
getDate("thisYear");
}
//获取推送时间段
function getDate(type){
var kssj,jssj;
var today = new Date();
var DAY = 1000*60*60*24;
if(type =="thisDay") { //当天
kssj = new Date();
jssj = new Date();
}
if(type == "thisWeek") { //本周周
kssj = getThisWeekFirstDay();//本周第一天
jssj = new Date();
}
if(type == "thisMonth") { //本月
kssj = getThisMonthFirstDay();//本月第一天
jssj = new Date();
}
if(type == "thisYear") { //本年
kssj = getThisYearFirstDay();//本年第一天
jssj = new Date();
}
var dateFrom = kssj.format('yyyy-MM-dd');
var dateTo = jssj.format('yyyy-MM-dd');
document.getElementById("dateFrom").value=dateFrom;
document.getElementById("dateTo").value=dateTo;
}
function getThisWeekFirstDay() {
var now = new Date();
var day = now.getDay();
var week = "1234567";
var first = 0 - week.indexOf(day);
var thisWeekfirstDay = new Date;
thisWeekfirstDay.setDate (thisWeekfirstDay.getDate () + first);
return thisWeekfirstDay;
}
function getThisMonthFirstDay(){
var date=new Date();
date.setDate(1);
return date;
}
function getThisYearFirstDay() {
var currentDate=new Date();
var currentYear=currentDate.getFullYear();
var currentYearFirstDate=new Date(currentYear,0,1);
return currentYearFirstDate;
}
//data类型转string
Date.prototype.format = function(format)
{
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
(this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1 ? o[k] :
("00"+ o[k]).substr((""+ o[k]).length));
return format;
}
</script>
</body>
</html>