获取日期区间的日期列表

  1. 判断日期格式是否正确,可以使用正则表达式
  const isDate = function(date) {
    const regExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
    return regExp.test(date) && !isNaN(new Date(date).getTime());
  };

或者使用日期校验方法

  const isCheckDate = function(date) {
    const res = date.match(/^(\d{1,4})(\-|\/|\.)(\d{1,2})\2(\d{1,2})$/);
    if (res !== null) {
      const tmpDate = new Date(res[1], parseInt(res[3]) - 1, res[4]);
      return tmpDate.getFullYear() === parseInt(res[1]) && tmpDate.getMonth() + 1 === parseInt(res[3]) && tmpDate.getDate() === parseInt(res[4]);
    }
    return false;
  };
  1. 获取日期区间的日期列表,
const getDateIntervalsList = function(startDate, endDate) {
  const isDate = function(date) {
    const regExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
    return regExp.test(date) && !isNaN(new Date(date).getTime());
  };
  const dateList = [];
  if (isDate(startDate) && isDate(endDate)) {
    const sT = new Date(startDate);
    const eT = new Date(endDate);
    while (eT.getTime() - sT.getTime() >= 0) {
      const year = sT.getFullYear();
      const month = (sT.getMonth() + 1).toString().padStart(2, '0');
      const day = (sT.getDate()).toString().padStart(2, '0');
      dateList.push(year + '-' + month + '-' + day);
      sT.setDate(sT.getDate() + 1);
    }
  }
  return dateList;
};
···
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容