前言
最近在做统计报表模块,其中查询条件用到了快速查询,主要为了方便客户统计查询常用的几个日期纬度,比如本周、上周、本月、上月、昨日。 使用js计算,主要用到了js Date、 getDate()、getDay(), 代码包括格式化日期函数。
快速查询日期计算
function NewDate(str)
{
str=str.split('-');
var date=new Date();
date.setUTCFullYear(str[0], str[1]-1, str[2]);
date.setUTCHours(0, 0, 0, 0);
return date; } //格式化日期格式 stime=stime.format("yyyyMMdd");
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;
} var curDateTime = new Date();
var nowYear = curDateTime.getFullYear();
var nowMonth = curDateTime.getMonth();
var nowDay = curDateTime.getDate();
var nowDayOfWeek = curDateTime.getDay(); console.log('year:'+nowYear+',month:'+nowMonth+',day:'+nowDay+',dayofweek:'+nowDayOfWeek); var start=new Date(),end=new Date();
//1昨天
//curDateTime.setDate(curDateTime.getDate()-1);
//start=curDateTime.format("yyyyMMdd");
//end=curDateTime.format("yyyyMMdd");
//console.log("昨天:"+start+" "+end); //2前天
//curDateTime.setDate(curDateTime.getDate()-2);
//start=curDateTime.format("yyyyMMdd");
//end=curDateTime.format("yyyyMMdd");
//console.log("前天:"+start+" "+end); //本周
//start=new Date(nowYear,nowMonth,(nowDay-nowDayOfWeek+1));
//start=start.format("yyyyMMdd");
//end==new Date(nowYear,nowMonth,curDateTime.getDate());
//end=end.format("yyyyMMdd");
//console.log("本周:"+start+" "+end); //上周
//start=new Date(nowYear,nowMonth,(nowDay-nowDayOfWeek-6));
//start=start.format("yyyyMMdd");
//curDateTime.setDate(nowDay-nowDayOfWeek);
//end=curDateTime.format("yyyyMMdd");
//console.log("上周:"+start+" "+end); //本月
//start=curDateTime.format("yyyyMM01");
//本月的截至日期只统计到当前
//end=curDateTime.format("yyyyMMdd");
//console.log("本月:"+start+" "+end); //上月
start =new Date(nowYear,nowMonth-1,1);
start=start.format("yyyyMMdd");
end=new Date(nowYear,nowMonth,1);
end.setDate(end.getDate()-1);
end=end.format("yyyyMMdd");
console.log("上月:"+start+" "+end);