实用时间工具函数:每隔一段时间 生成时间段数组

使用场景:如场地预约,以半小时为间隔,需要输入场地可预约的开始时间和结束时间。输出如“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秒"
 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值