第 134 题:求两个日期中间的有效日期

发布于 2022-10-22 19:50:43 字数 46 浏览 50 评论 40

如 2015-2-8 到 2015-3-3,返回【2015-2-8 2015-2-9...】

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(40

乙白 2022-05-04 13:54:44

toLocaleDateString

function getEffectiveDate(start,end){
  let startTime = new Date(start.replace(/-/g,"/")).getTime(),
      endTime = new Date(end.replace(/-/g,"/")).getTime();
  if(startTime>endTime){
    return;
  }
  while(startTime<=endTime){
    console.log(new Date(startTime).toLocaleDateString().replace(///g,"-"));
    startTime+=3600*24*1000;
  }
}
getEffectiveDate("2019-2-5","2019-3-4");
终难遇 2022-05-04 13:54:44
function toString() {
  return Array.prototype.join.call(arguments, "-");
}

function findBetween(from, to) {
  const date1 = new Date(from),
    date2 = new Date(to);

  const oneDay = 24 * 60 * 60 * 1000;
  let curr = +date1;
  const end = +date2;
  const result = [];
  while (curr <= end) {
    const now = new Date(curr);
    result.push(toString(now.getFullYear(), now.getMonth() + 1, now.getDate()));
    curr += oneDay;
  }
  return result;
}
如果没有你 2022-05-04 13:54:44
export function toDate(string) {
    const args = string.split(/[/:-s]/);
    args[1] -= 1;
    return new Date(...args);
}

export function getDateTime(date = new Date()) {
    const times = date.getTime() - date.getTimezoneOffset() * 6e4;
    return new Date(times).toISOString().slice(0,19).replace('T', ' ')
}

const ONE_DAY = 86400000;
export function getOffsetDayDate(offset = 0, start = new Date()) {
    const times = start.getTime();
    return new Date(offset * ONE_DAY + times);
}

function getDateRanges(start, end) {
    const begin = toDate(start);
    const over = toDate(end);
    let next = begin;
    const ret = [];
    while (next <= over) {
        ret.push(getDateTime(next).slice(0,10));
        next = getOffsetDayDate(1, next);
    }
    return ret;
}
一张白纸-° 2022-05-04 13:54:44

const getTime = (time1,time2) =>{
let arr = [];
let t1 = new Date(time1).getTime();
let t2 = new Date(time2).getTime();

    while( (t1+=24*60*60*1000) <t2 ) {
        arr.push(new Date(t1).toLocaleDateString().replace(///g,'-'))
    }

    return arr;
}
孤蝉 2022-05-04 13:54:44
// 解题
function getValidDate (fromDate, toDate) {
    let f = new Date(fromDate);
    let t = new Date(toDate);
    const res = [myDate(f)]
    while (t.getTime()  !== f.getTime()){
        f.setDate(f.getDate() + 1);
        res.push(myDate(f));
    }
    console.log(res.join(' '));
}

function myDate (dateObj) {
    return dateObj.getFullYear() + '-' + Number(dateObj.getMonth() + 1) + '-' + dateObj.getDate();
}
冷清清 2022-05-04 13:54:44
    let test = (start, end) => {
        let startDate = new Date(start);
        let endDate = new Date(end);
        let length = (endDate - startDate) / (24 * 60 * 60 * 1000) + 1;

        return Array.from({length}).map((item, index) => {
            let result = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + index);
            return `${result.getFullYear()}-${result.getMonth() + 1}-${result.getDate()}`
        });
    };
    let startDate = '2015-2-8', endDate = '2015-3-3';
    console.info(test(startDate, endDate))
莫相离 2022-05-04 13:54:44
  function getValidDate(startDate, endDate) {
    let rst = [],
      startDateTmp = (new Date(startDate)).valueOf(),
      endDateTmp = (new Date(endDate)).valueOf(),
      validDateTmp = startDateTmp;
    while (validDateTmp < endDateTmp) {
      const tmpTime = new Date(validDateTmp)
      let validDate = tmpTime.getFullYear();
      validDate += `-${tmpTime.getMonth() + 1}`;
      validDate += `-${tmpTime.getDate()}`;
      rst.push(validDate);
      validDateTmp = validDateTmp + 1000 * 60 * 60 * 24;
    }
    return rst;
  }
岁月静好 2022-05-04 13:54:44
function getExpiresDate(day1, day2) {
    let startDate = +new Date(new Date(day1).toLocaleDateString())
    let endDate = +new Date(new Date(day2).toLocaleDateString())
    let expiresArr = [], tempDate = startDate + 24*60*60*1000
    while (tempDate < endDate) {
        expiresArr.push(new Date(tempDate).toLocaleDateString().replace(///g, '-'))
        tempDate += 24*60*60*1000
    }
    return expiresArr;
}
getExpiresDate('2019-10-01 02:00:00', '2019-10-11 00:00:00')
getExpiresDate('2019-10-01', '2019-10-11')
十二 2022-05-04 13:54:44
/**
求两个日期中间的有效日期
如 2015-2-8 到 2015-3-3,返回【2015-2-8 2015-2-9...】
 */
const start = '2015-2-8'
const end = '2015-3-3'

function getDates (start, end) {
  const startMS = new Date(start).getTime()
  const endMS = new Date(end).getTime()
  const diff = endMS - startMS

  const oneDay = 1000 * 60 * 60 *24
  let num = diff / oneDay

  const dates = []

  let first = startMS
  while (num) {
    const cur = new Date(first)
    const y = cur.getFullYear()
    const m = cur.getMonth() + 1
    const d = cur.getDate()
    const date = `${y}-${m}-${d}`
    dates.push(date)

    first += oneDay
    num--
  }
  console.log(dates)
}

getDates(start, end)
凉墨 2022-05-04 13:54:44
// 如 2015-2-8 到 2015-3-3 返回【2015-2-8 2015-2-9...】
function rangeTime (start, end) {
	start = start.replace('-','/');
	end = end.replace('-','/');
	var ret = [];
	var setp = 24 * 3600 * 1000;
	var startStmp = Math.min(Date.parse(new Date(start)), Date.parse(new Date(end)));
	var endStmp = Math.max(Date.parse(new Date(start)), Date.parse(new Date(end)));
	if (startStmp === endStmp) return [];
	ret.push(startStmp);
	while(ret[ret.length  - 1] + setp < endStmp) {
		ret.push(ret[ret.length  - 1] + setp);
	}
	ret.push(endStmp);
	return ret.map(function(item){
		return new Date(item).toLocaleDateString().replace(/(/)|年|月/g, '-').replace('日', '')
	});
}
console.log(rangeTime('2015-2-8', '2015-3-3'));
岁月ツ蹉跎了容颜。 2022-05-04 13:54:44

我这个性能比较差

function getAllDate(day1,day2) {
  let date1 = +new Date(day1)
  const date2 = +new Date(day2)
  const result = []
  let next = null
  while(date1 <= date2) {
    date1 += 86400000
    next = new Date(date1)
    let year = next.getUTCFullYear()
    let month = next.getUTCMonth() + 1
    let day = next.getUTCDate()
    result.push(`${year}-${month}-${day}`)
  } 
  return result
}

console.log(getAllDate('2015-2-8','2015-3-3'))
淡写薰衣草的香 2022-05-04 13:54:44

利用时间戳,24 * 60 * 60 * 1000,得到下一天时间戳。

var start = '2015-2-8'
var end = '2015-3-3'

function getDate(start, end) {
  const startDate = new Date(start)
  const endDate = new Date(end)
  let nextDate = startDate
  let result = []

  while(nextDate.getTime() !== endDate.getTime()) {
    result.push(nextDate.toLocaleDateString().replace(/(/)/g, '-'))
    nextDate = new Date(new Date(nextDate).getTime() + 24 * 60 * 60 * 1000)
  }
  result.push(endDate.toLocaleDateString().replace(/(/)/g, '-'))
  console.log(result)
}

getDate(start, end)
墨落画卷 2022-05-04 13:54:44
f = (s, e) => {
    const dayUnit = 24 * 60 * 60 * 1000;
    const dayNums = (new Date(e) - new Date(s)) / dayUnit;

    let n = 0;
    const res = [];

    while (n <= dayNums) {
        const nday = new Date(+new Date(s) + dayUnit * n)
        const nday_formated = nday.toLocaleDateString().replace(///g, '-');
        res.push(nday_formated)
        n++;
    }

    return res;
}
// f('2010','2011')
// f('2010-2','2010-3')
f('2010-3-1', '2010-3-15')
在你怀里撒娇 2022-05-04 13:54:44
const getDate = (d1,d2)=>{
    const result = [];
    let timeStart = new Date(d1);
    let timeEnd = new Date(d2);
    while (timeStart < timeEnd) {
        timeStart.setDate(timeStart.getDate()+1);
        result.push(`${timeStart.getFullYear()}-${timeStart.getMonth() + 1}-${timeStart.getDate()}`)
    }
    result.pop();
    return result;
}
空袭的梦i 2022-05-04 13:54:44
function getDateAry(day1, day2) {
    const date1 = new Date(day1);
    const date2 = new Date(day2);
    const oneDay = 1000 * 60 * 60 * 24;
    const duration = (date2.getTime() - date1.getTime()) / oneDay;
    const res = [];
    for (let i = 0; i <= duration; i++) {
      const day = new Date(date1.getTime() + oneDay * i);
      res.push(day.toLocaleDateString().replace(///g, '-'))
    }
    return res;
  }
汐鸠 2022-05-04 13:54:44

function rangeDay (day1, day2) {
const result = []
const dayTimes = 246060*1000
let startTime = day1.getTime()
const endTime = day2.getTime()
while (startTime <= endTime) {
result.push(new Date(startTime).toLocaleDateString().replace(///g, '-'))
startTime += dayTimes;
}
return result
};
console.log(rangeDay(new Date("2015-02-02"), new Date("2015-02-08")));

肥爪爪 2022-05-04 13:54:44
const DAY_TIME = 1000 * 60 * 60 * 24

function range(date1, date2) {
    let d1 = +new Date(date1)
    let d2 = +new Date(date2)
    if (d2 < d1) {
        [d1, d2] = [d2, d1]
    }
    const res = []
    for (let i = d1 + DAY_TIME; i < d2; i+= DAY_TIME) {
        const tmp = new Date(i)
        res.push(`${tmp.getFullYear()}-${tmp.getMonth() + 1}-${tmp.getDate()}`)
    }
    return res
}
笑脸一如从前 2022-05-04 13:54:44
function formatDate(time) {
  const date = new Date(time);

  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
};

function rangeDay(day1, day2) {
  let time1 = new Date(day1).getTime();
  const time2 = new Date(day2).getTime();
  const day = 1000 * 60 * 60 * 24;
  const result = [];

  while (time2 >= time1) {
    result.push(formatDate(time1));
    time1 += day;
  }

  return result;
}

rangeDay("2015-2-8", "2015-3-3");
骄傲 2022-05-04 13:54:42
function getAllDays(from, to) {
  const res = [];
  let current = Date.parse(from);
  const toTimeStamp = Date.parse(to);
  while((current += 86400000) <= toTimeStamp) {
    res.push(new Date(current).toISOString().split('T')[0]);
  }
  return res;
}
记忆で 2022-05-04 13:54:19
function effective(start_data,end_data){
	if(!Date.parse(start_data) || !Date.parse(end_data)){ return '非日期格式'; }
	let start = (new Date(start_data)).getTime(),
	end = (new Date(end_data)).getTime(),returnDate = [];
	if(start >= end){ return [] }
	let days = parseInt((end-start)/(1000*60*60*24));
	for(let i=0;i<=days;i++){
		flag = start + i* 1000*60*60*24;
		let t = new Date(flag),y = t.getFullYear(),m = t.getMonth() + 1,d = t.getDate();
		returnDate.push(y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d));
	}
	return returnDate
}

console.log(effective('2015-2-2','2015-3-3'))
梓梦 2022-05-04 13:52:52
       function getRange(start, end){
            const rangeArr = [];
            rangeArr.push(start);
            while(start!=end){
                let [currYear, currMonth, currDay] = start.split('-');
                currDay++;
                let dayLength = 0;
                const monthLength = 12;
                const isLeapYear = currYear%4===0;
                switch(currMonth){
                    case '1':
                    case '3':
                    case '5':
                    case '7':
                    case '8':
                    case '10':
                    case '12':
                        dayLength = 31;
                        break;
                    case '4':
                    case '6':
                    case '9':
                    case '11':
                        dayLength = 30;
                        break;
                    case '2':
                        dayLength = isLeapYear ? 29 : 28;
                        break;
                }
                if(currDay > dayLength){
                    currMonth++;
                    currDay = 1;
                    if(currMonth > monthLength){
                        currYear++;
                        currMonth = 1;
                    }   
                }
                start = currYear+'-'+currMonth+'-'+currDay;
                rangeArr.push(start);
            }
            return rangeArr; 
        }
暮凉 2022-05-04 13:51:36
const rangeDay = (day1 = new Date, day2 = new Date) => {
    const oneDay = 1000 * 60 * 60 * 24
    const maxDay = (...rest) => rest.map(v => new Date(v)).sort((a, b) => a - b)
    const [min, max] = maxDay(day1, day2)
    const range = (+max - +min) / oneDay
    const res = []
    const dayFormatter = date => (date = new Date(date),
        `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, 0)}-${String(date.getDate()).padStart(2, 0)}`
    )
    for (let i = 0; i <= range; i++) {
        res.push(dayFormatter(+min + oneDay * i))
    }
    return res
}

console.log(rangeDay('2018-05-01', '2018-02-01'))
逆流。 2022-05-04 13:48:48
const getRangeDate = (startDate, endDate) => {
    let startTime = new Date(startDate.replace('-', '/')).getTime()
    let endTime = new Date(endDate.replace('-', '/')).getTime()
    const day = 24 * 60 * 60 * 1000
    const res = []

    while (startTime <= endTime) {
        const d = new Date(startTime)
        res.push(`${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}`)
        startTime += day
    }
    return res
}
江南烟雨〆相思醉つ 2022-05-04 13:31:57
function getMiddleDate(start, end) {
  start = new Date(start).getTime()
  end = new Date(end).getTime()
  if (!start || !end) return
  if (start > end) {
    [start, end] = [end, start]
  }
  let dayMillSec = 24 * 60 * 60 * 1000
  let result = []
  while (start <= end) {
    result.push(new Date(start).toLocaleDateString().replace(///g, '-'))
    start = start + dayMillSec
  }
  return result
}
console.log(getMiddleDate('2015-2-8', '2015-3-3'))
╰ゝ天使的微笑 2022-05-04 13:26:37

//题目开放,变式很多了
const dateTransfer = (start, end) => {
const distance = 1000 * 60 * 60 * 24;
const startTime = new Date(start).getTime();
const endTime = new Date(end).getTime();
const result = [];

while(startTime < endTime){
    result.push(new Date(startTime + distance).toLocaleDateString().replace(///g, '-'));
    startTime +=  distance;   
}
return result;

}

dateTransfer('2019-08-01', '2019-08-30')

∞琼窗梦回ˉ 2022-05-04 12:07:00
/* 2015-2-8 到 2015-3-3,返回【2015-2-8 2015-2-9...】之间的日期*/
function getRangeDate(start, end) {
    let onDay = 24 * 60 * 60 * 1000;  
    dateStr = "[";
    start = + new Date(start);
    end = + new Date(end);
    while(start <= end) {
        let cur = new Date(start);
        dateStr += `${cur.getFullYear()}-${cur.getMonth() + 1}-${cur.getDate()} `;
        start += onDay;
    }
    console.log(dateStr.slice(0, -1) + "]")
} 

let start = "2015-2-8";
let end = "2015-3-3";
getRangeDate(start, end) //[2015-2-8 2015-2-9 2015-2-10 2015-2-11 2015-2-12 2015-2-13 2015-2-14 2015-2-15 2015-2-16 2015-2-17 2015-2-18 2015-2-19 2015-2-20 2015-2-21 2015-2-22 2015-2-23 2015-2-24 2015-2-25 2015-2-26 2015-2-27 2015-2-28 2015-3-1 2015-3-2 2015-3-3]
梦一生花开无言 2022-05-04 10:52:56
function getDate(startDay, endDay) {
        let dateArr = [],
            start = Date.parse(new Date(startDay)),
            end = Date.parse(new Date(endDay));
        const oneDay = 60 * 60 * 24 * 1000;
        while (start <= end) {
            let item = [],
                startObj = new Date(start);
            item.push(startObj.getFullYear());
            item.push(startObj.getMonth() + 1);
            item.push(startObj.getDate());
            dateArr.push(item.join('-'));
            start += oneDay;
        }
        return dateArr;
    }
    console.log(getDate('2000-7-20', '2019-8-30'));
捎一片雪花 2022-05-04 10:06:05
const getDateValueOf = (day) => new Date(day).valueOf()
const setLocalStringDate = (value) => new Date(value).toLocaleDateString().replace(///g,'-')

const getDate = (startDay, endDay) => {
    const standardDayValue = 86400 * 1000;
    if (getDateValueOf(startDay) > getDateValueOf(endDay)) {
        return 'input value is not vaild date'
    }
    const intervalDayValue = (getDateValueOf(endDay) - getDateValueOf(startDay)) / standardDayValue
    return Array.from({length: intervalDayValue + 1}).map((item, index) => index * standardDayValue + getDateValueOf(startDay)).map(item => setLocalStringDate(item))
}


getDate('2019-8-29', '2019-10-10')
鹿港小镇 2022-05-04 08:50:05
function getDays(start,end){
  let startTime = new Date(start)
  let endTime = new Date(end)
  let days = []
  while(startTime<=endTime){
    days.push(startTime.getFullYear()+'-'+(startTime.getMonth()+1)+'-'+startTime.getDate())
    startTime.setDate(startTime.getDate()+1)
  }
  return days
}

getDays('2015-2-8','2015-3-3')
温馨耳语 2022-05-04 07:44:56
let valiableDay = (start,end) => {
            let result = [];
            let onedaySeconds = 24*60*60*1000;
            let startTime = new Date(start).getTime();
            let endTime = new Date(end).getTime();
            let range = endTime - startTime;
            let i = 0;
            while(i <= range && range > 0) {
                result.push(new Date((startTime + i )).toLocaleDateString().replace(///g,'-'));
                 i += onedaySeconds;
            }
            return result;
        };
        let res = valiableDay("2015-02-08","2015-03-03");
        console.log(res);
盗琴音 2022-05-04 05:18:07

function getDays (startDate, endDate) {
let startDateTime = new Date(startDate).getTime()
let endDateTime = new Date(endDate).getTime()
if (isNaN(startDateTime) || isNaN(endDateTime)) {
return '输入的日期不合法'
}
if (endDateTime < startDateTime) {
return '开始时间不能大于结束时间'
}
let days = []
let day = startDateTime
let count = (endDateTime - startDateTime) / 1000 / 60 / 60 / 24
for (let i = 0; i < count; i++) {
day = day + 24 * 60 * 60 * 1000
days.push(new Date(day).toLocaleDateString().replace(///g, '-')) // 这里用 转译一下
}
days.pop()
return days
}

帝王念 2022-05-04 02:40:51

import moment from 'moment';
写一个用moment的

getAllDays = (startTime, endTime) => {
    if (moment(startTime).isBefore(endTime, 'day') || moment(startTime).isSame(endTime, 'day')) {
      let configTime = moment(startTime);
      const allMonths = [configTime.format('YYYY-MM-DD')];
      while(configTime.isBefore(endTime, 'd')){
        configTime = configTime.add(1, 'd');
        allMonths.push(configTime.format('YYYY-MM-DD'));
      }
      return allMonths;
    }
    return [];
  };

So尛奶瓶¬ε¬ 2022-05-04 00:45:12
  • 代码如下
    //2015-2-8 2015-3-3
    function rangeDate(startDate, endDate) {
        let start_ = new Date(startDate).getTime();
        let end_ = new Date(endDate).getTime();
        let day = 24 * 60 * 60 * 1000;
        let arr = [];
        for (let i = start_; i <= end_; i += day) {
            arr.push(i);
        }
        return arr.map(item => {
            let date = new Date(item);
            let year = date.getFullYear();
            let month = (date.getMonth() + 1);
            let day = date.getDate();
            return `${year}-${month}-${day}`;
        });
    }

    console.log(rangeDate("2015-2-8", "2015-3-3"));
噩梦成真你也成魔 2022-05-03 19:27:32

function getTimeList(startTime, endTime) {
let dayList = []
let count = (new Date(endTime).getTime() - new Date(startTime).getTime()) / 1000 / 86400
for (let i=0; i<=count; i++) {
let day = new Date(startTime).getTime() + i100086400
dayList.push(formatDate(day))
}
return dayList
}

function formatDate(now) {
let day = new Date(now)
var year = day.getFullYear();
var month = day.getMonth() + 1;
var date = day.getDate();
return year + "-" + month + "-" + date;
}

console.log(getTimeList('2015-2-8','2015-3-3'))

疑心病 2022-05-02 19:08:52
      function toDateList(startTime, endTime) {
        // 2019-1-1 这种格式在ios是不兼容的Invalid Date。
        let startTimeStamp = new Date(startTime.replace(/-/g, '/')).getTime(),
          endTimeStamp = new Date(endTime.replace(/-/g, '/')).getTime(),
          dateList = []

        if (startTimeStamp > endTimeStamp) {
          return false
        }

        while (startTimeStamp !== endTimeStamp) {
          startTimeStamp += 24 * 60 * 60 * 1000

          let date = new Date(startTimeStamp)
            .toLocaleDateString()
            .replace(///g, '-')

          dateList.push(date)
        }

        return dateList
      }
      console.log(toDateList('2015-2-8', '2015-3-9'))
美羊羊 2022-05-02 02:34:47

const getDate = (start,end) => { const result = [] start = new Date(start).getTime() end = new Date(end).getTime() for(let i = start;i<=end;i+=(24*60*60*1000)){ let date = new Date(i) result.push(date.getFullYear()+'-'+(date.getMonth() + 1)+'-'+(date.getDate())) } return result }

["2018-2-8", "2018-2-9", "2018-2-10", "2018-2-11", "2018-2-12", "2018-2-13", "2018-2-14", "2018-2-15", "2018-2-16", "2018-2-17", "2018-2-18", "2018-2-19", "2018-2-20", "2018-2-21", "2018-2-22", "2018-2-23", "2018-2-24", "2018-2-25", "2018-2-26", "2018-2-27", "2018-2-28", "2018-3-1", "2018-3-2", "2018-3-3"]

上课铃就是安魂曲 2022-05-01 10:38:53
function rangeDay (day1, day2) {
   const result = []
    const dayTimes = 24*60*60*1000
    const startTime = day1.getTime()
    const range = day2.getTime() - startTime
    let total = 0
    
    while (total <= range && range > 0) {
        result.push(new Date(startTime + total).toLocaleDateString().replace(///g, '-'))
        total += dayTimes
    }
   return result
};
rangeDay(new Date("2015-02-08"), new Date("2015-03-03"))

["2015-2-8", "2015-2-9", "2015-2-10", "2015-2-11", "2015-2-12", "2015-2-13", "2015-2-14", "2015-2-15", "2015-2-16", "2015-2-17", "2015-2-18", "2015-2-19", "2015-2-20", "2015-2-21", "2015-2-22", "2015-2-23", "2015-2-24", "2015-2-25", "2015-2-26", "2015-2-27", "2015-2-28", "2015-3-1", "2015-3-2", "2015-3-3"]

~没有更多了~

关于作者

0 文章
0 评论
23 人气
更多

推荐作者

烙印

文章 0 评论 0

singlesman

文章 0 评论 0

独孤求败

文章 0 评论 0

晨钟暮鼓

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文