使用场景:如场地预约,以半小时为间隔,需要输入场地可预约的开始时间和结束时间。输出如“8:30-9:00”、“9:00-9:30”这类字段
IOS需要注意 不能转换'2023-8-8'这种格式 要换成'2023/8/8'
使用replace(/-/g,'/')先转换
//工具类函数
// 格式化时间-小于10补0
function formatDigit(n) {
return n.toString().replace(/^(\d)$/, '0$1');
}
// 格式化时间,通用
const formatDate = (timestamp, formats) => {
/*formats格式
1. Y-M-D
2. Y-M-D h:m:s
3. Y年M月D日
4. Y年M月D日 h时m分
5. Y年M月D日 h时m分s秒
示例:console.log(formatDate(new Date().getTime(), 'Y年M月D日 h:m:s')) ==> 2023年5月17日 11:00:00
*/
formats = formats || 'Y-M-D';
let myDate = undefined;
if (timestamp) {
if (typeof (timestamp) != 'string') {
myDate = timestamp;
} else {
myDate = new Date(timestamp);
}
} else {
myDate = new Date();
}
const year = myDate.getFullYear();
const month = formatDigit(myDate.getMonth() + 1);
const day = formatDigit(myDate.getDate());
const hour = formatDigit(myDate.getHours());
const minute = formatDigit(myDate.getMinutes());
const second = formatDigit(myDate.getSeconds());
return formats.replace(/Y|M|D|h|m|s/g, (matches) => {
return {
Y: year,
M: month,
D: day,
h: hour,
m: minute,
s: second
}[matches];
});
}
//最终调用的函数
const createTimeArray=function(startTime,endTime,minutes,formats,date=new Date()){
//格式化标准时间 头部
const frontTime=formatDate(date,'Y/M/D')
//获得时间戳
let startDate = new Date(frontTime+' '+formatDigit(startTime)).getTime();
let endDate=new Date(frontTime+' '+formatDigit(endTime)).getTime();
//所隔时间
const space = minutes * 60 * 1000;
let mod = endDate - startDate;
let modNum=mod/space
let dateArray = [];
for(let i=0;i+1<=modNum;i++){
const start=startDate+space*i
const end=startDate+space*(i+1)
//在这里输出可以自行修改拼接最终输出时间格式 这里仅仅是以数组为例
let final=formatDate(new Date(start),formats)+'-'+formatDate(new Date(end),formats)
dateArray.push(final)
}
console.log('dateArray',dateArray)
return dateArray
}
//使用示例
createTimeArray('8:30:00','10:00:00',30,'h:m')
//['08:30-09:00', '09:00-09:30', '09:30-10:00']
createTimeArray('8:30:00','10:00:00',30,'Y-M h:m','2023/10/23')
//['2023-10 08:30-2023-10 09:00', '2023-10 09:00-2023-10 09:30', '2023-10 09:30-2023-10 10:00']
传入开始时间startTime,结束时间endTime,
时间间隔minutes(分钟),输出时间格式formats
日期date(可选) 传入标准时间或时间戳都可
根据功能可自行调整输出,函数逻辑都不难。
格式化函数中
formats格式(字符串)
- Y-年份
- M-月份
- D-日
- h-时
- m-分
- s-秒
请自行自由组合
格式示例如下
1."Y-M-D"
2."Y-M-D h:m:s"
3."Y年M月D日"
4."Y年M月D日 h时m分"
5."Y年M月D日 h时m分s秒"