这里时间插件你们自己定义
代码如下
Date.prototype.Format = function(fmt)//日期格式
{
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)) {
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
};
function getTimeArr(begin,end,type,interval){ //获取两个时间相邻的数组 type:目前可传"yyyy-MM-dd hh" "yyyy-MM-dd" "yyyy-MM"格式的时间
var arr=[];
if(type=="yyyy-MM-dd hh"){//设置小时间隔
var beginDate=new Date(begin+" 00:00");
var endDate=new Date(end+" 23:59");
var msCount=interval*60*60*1000; //1小时 2小时 3小时
}else if(type=="yyyy-MM-dd hh:mm"){//设置分钟间隔
var beginDate=new Date(begin+" 00:00");
var endDate=new Date(end+" 23:59");
var msCount=interval*60*1000; //30分钟 10分钟 5分钟 15分钟
}else if(type=="yyyy-MM-dd"){//设置天间隔
var beginDate=new Date(begin+" 00:00");
var endDate=new Date(end+" 00:00");
var msCount=interval*24*60*60*1000; //1天 2天 3天
}else if(type=="yyyy-MM"){//获取月间隔
var startDate=begin.split("-");
var endDate1=end.split("-");
var intervalMonth = (parseInt(endDate1[0]*12)+parseInt(endDate1[1])) - (parseInt(startDate[0]*12)+parseInt(startDate[1]));
arr=getMonthArr(end,intervalMonth+1);
return arr;
}else if(type=="yyyy"){//获取年间隔
for(var i=parseInt(begin);i<=parseInt(end);i++){
arr.push(i.toString());
}
return arr;
}
var beginMs=beginDate.getTime();
var endMs=endDate.getTime();
for(var i=beginMs;i<=endMs;i+=msCount){
if(type=="yyyy-MM-dd hh"){
arr.push(new Date(i).Format(type)+":00");
}else if(type=="yyyy-MM-dd hh:mm"){
arr.push(new Date(i).Format(type));
}
else if(type=="yyyy-MM-dd"){
arr.push(new Date(i).Format(type));
}
}
return arr;
}
function getMonthArr(sDate,n){//得到最近n个月份的数组
var arr=[];
sDate=sDate.slice(0,7);
arr.push(sDate);
while(n>1){
arr.unshift(getBeforMonth(sDate));
sDate=getBeforMonth(sDate);
n--;
}
return arr;
}
function getBeforMonth(date){
var lastMonth="";
var year=date.split("-")[0],month=date.split("-")[1];
if(month==1){
lastMonth=(year-1)+"-"+12;
}else{
lastMonth=year+"-"+add0(month-1);
}
return lastMonth;
}
方法调用如下
首先 返回以小时为间隔的时间数组
这里开始时间为2019-08-28 结束时间 2019-08-29
console.log(getTimeArr(startTime,endTime,'yyyy-MM-dd hh',1))//1小时
返回格式可自行修改
然后返回以分钟为间隔的时间数组
这里开始时间为2019-08-28 结束时间 2019-08-29
console.log(getTimeArr(startTime,endTime,'yyyy-MM-dd hh:mm',5))//5分钟
再测试一个 15分钟;
console.log(getTimeArr(startTime,endTime,'yyyy-MM-dd hh:mm',15))//15分钟
以天为时间间隔的
console.log(getTimeArr(startTime,endTime,'yyyy-MM-dd',1))//1天
console.log(getTimeArr(startTime,endTime,'yyyy-MM-dd',2))//2天
以月为时间间隔的
这里我特意选了一个跨年的
console.log(getTimeArr(startTime,endTime,'yyyy-MM'))
最后就是以年为时间间隔的
console.log(getTimeArr(startTime,endTime,'yyyy'))
最后就是返回格式的问题 这个可以根据自己的需求去改
希望可以帮助大家