【js】--获取开始时间 和 截止时间中间的所有时间
1.工具函数 将【中国标准时间】 转换成 【年月日 时分秒】
/*
* timeStamp: 标准时间 例: 'Tue Sep 22 2020 00:00:00 GMT+0800 (中国标准时间)'
* fmt: 时间格式
*/
function dealFormData(timeStamp, fmt = 'Y-m-d h:00:00') {
const date = new Date(timeStamp);
const tmpYear = date.getFullYear();
const tmpMon = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1);
const tmpDay = (date.getDate() > 9) ? date.getDate() : '0' + (date.getDate());
const tmpHour = (date.getHours()) > 9 ? date.getHours() : '0' + (date.getHours());
const tmpMinutes = (date.getMinutes()) > 9 ? date.getMinutes() : '0' + (date.getMinutes());
const tmpSeconds = (date.getSeconds()) > 9 ? date.getSeconds() : '0' + (date.getSeconds());
let finalData = '';
switch (fmt) {
case 'Y-m-d h:m:s':
finalData = tmpYear + '-' + tmpMon + '-' + tmpDay + ' ' + tmpHour + ':' + tmpMinutes + ':' + tmpSeconds;
break;
case 'Y-m-d h:00:00':
finalData = tmpYear + '-' + tmpMon + '-' + tmpDay + ' ' + tmpHour + ':00:00';
break;
case 'Y-m-d':
finalData = tmpYear + '-' + tmpMon + '-' + tmpDay;
break;
default:
//
}
return finalData;
}
2.判断函数,是否是【中国标准时间】 用到上面的 dealFormDate 方法
// 判断是否 中国标准时间
isChinaStandardTime(time, format) {
let temp = '';
// 判断 时间 是否是 时间字符串, 还是中国标准时间,是中国标准时间 就转换
if (time.indexOf('中国标准时间') !== -1) {
temp = dealFormData(time, format);
return temp;
}
return time;
},
3.得到中间的时间方法
// 得到中间的时间
/*
* type: 类型 'hour', 'day'
* startTime: 开始时间 例:'2020-09-22 00:00:00'
* endTime: 结束时间 例:'2020-09-23 23:00:00'
*/
getMiddleData(type, startTime, endTime) {
const dealTimeArr = [];
let dealStartTime = new Date(startTime).getTime();
const dealEndTime = new Date(endTime).getTime();
if (type === 'hour') {
while (true) {
if (dealStartTime <= dealEndTime) {
const itemTime = this.isChinaStandardTime((new Date(dealStartTime)).toString(), 'Y-m-d h:00:00');
dealTimeArr.push(itemTime);
// debugger;
dealStartTime += 1 * 60 * 60 * 1000;
} else {
break;
}
}
} else if (type === 'day') {
while (true) {
if (dealStartTime <= dealEndTime) {
const itemTime = this.isChinaStandardTime((new Date(dealStartTime)).toString(), 'Y-m-d');
dealTimeArr.push(itemTime);
// debugger;
dealStartTime += 24 * 60 * 60 * 1000;
} else {
break;
}
}
}
console.log(dealTimeArr);
},
4.调用
// 选完 小时数据的结束时间 时 调用接口
/*
* t: 中国标准时间,这是 element-ui 时间选择器的change方法,默认传进来的值
*/
queryHourData(t) {
this.choseTimeHour.startTime = this.isChinaStandardTime(this.choseTimeHour.startTime.toString(), 'Y-m-d h:00:00');
this.choseTimeHour.endTime = this.isChinaStandardTime(t.toString(), 'Y-m-d h:00:00');
console.log(this.choseTimeHour);
console.log('处理时间');
this.getMiddleData('hour', this.choseTimeHour.startTime, this.choseTimeHour.endTime);
},
element-ui 时间控件
<el-date-picker style="width:192px;" popper-class="dateRangeStyle"
v-model="choseTimeHour.endTime"
type="datetime" @change= "queryHourData"
placeholder="选择日期">
</el-date-picker>
用到的变量:
choseTimeHour: {
startTime: '',
endTime: '',
}
该方法是在使用 Vue框架的时候,用到的,为了便于查看,就写成了 传统js的样式,调用的时候,还是用 vue 的形式调用

浙公网安备 33010602011771号