当前日期的日期范围自定义功能

时间:2020-05-05 06:48:04

标签: javascript

我试图根据日期将函数写入列表数组,这意味着我需要将以下输出作为函数的返回值

const data = [
        {
            id: 1,
            week: 'Current Week', // Text Based on the Current year where the range lies
            displayText: '15th Mar - 21st Mar 2020', // Date Range
            rangeStart: '03/15/2020', // range start day
            rangeEnd: '03/21/2020', // range end day
        },
        {
            id: 2,
            week: 'Last Week',
            displayText: '8th Mar - 14th Mar 2020',
            rangeStart: '03/08/2020',
            rangeEnd: '03/14/2020',
        },
        {
            id: 3,
            week: 'Week 15',
            displayText: '1st Mar - 7th Mar 2020',
            rangeStart: '03/07/2020',
            rangeEnd: '03/01/2020',
        },
        {
            id: 4,
            week: 'Week 14',
            displayText: '23rd Feb - 29th Feb 2020',
            rangeStart: '02/29/2020',
            rangeEnd: '02/01/2020',
        },
    ];

因此该函数将主要使用三个参数

  1. 星期几开始// //默认值星期天
  2. 一周中的最后一天//默认值星期六
  3. 一周总计//默认值4
 getDateRangeList = (startDay = 'Sunday', endDay = 'Saturday', weeks = 4) => {
        let rangeDays = 7; // diff bw start day and end day
        let weeksToShow = Array.from({ length: weeks }, (_, i) => i + 1);
        let result = weeksToShow.map((week) => {
            let obj = {};
            obj['id'] = week;
            var startDate = new Date();
            startDate.setDate(week === 1 ? startDate.getDate() : startDate.getDate() - 7 * week);
            obj['rangeStart'] = startDate.toISOString().split('T')[0];
            var endDate = new Date();
            endDate.setDate(endDate.getDate() - 7 * week);
            obj['rangeEnd'] = endDate.toISOString().split('T')[0];
            return obj;
        });
        return result;
    };

达到此结果的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您不需要结束日期,因为您知道一周的时间是7天

getDateRangeList = (startDay = 1, weeks = 18, startDate = new Date()) => {
  let weeksToShow = Array.from({
    length: weeks
  }, (_, i) =>i);

  if (startDate.getDay() !== startDay) {
    startDate.setDate(startDate.getDate() - (startDate.getDay() - startDay))
  }

  return weeksToShow.map(week => {
    let [rangeStart, rangeEnd] = [new Date(startDate.getTime()), new Date(startDate.getTime())];
    rangeStart = new Date(rangeStart.setDate(rangeStart.getDate() - (7 * week)));
    rangeEnd = new Date(rangeEnd.setDate(rangeEnd.getDate() - (7 * (week - 1))));

    return {
      id: week,
      week: week === 1 ? 'Current Week' : week === 2 ? 'Last Week' : getWeekNumber(rangeStart),
      displayText: `${getDisplayTest(rangeStart)} - ${getDisplayTest(rangeEnd)}`,
      rangeStart: rangeStart.toISOString().split('T')[0].split('-').join('/'),
      rangeEnd: rangeEnd.toISOString().split('T')[0].split('-').join('/'),
    }
  });
};

// Copied from https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php
function getWeekNumber(d) {
  d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
  const dayNum = d.getUTCDay() || 7;
  d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  return Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
}

function getDisplayTest(d) {
  const [day, month, [firstDateChar, secondDateChar], year] = d.toDateString().split(" ");
  const suffix = !secondDateChar ?
    +firstDateChar === 1 ? 'st' : +firstDateChar === 2 ? 'nd' : +firstDateChar === 3 ? 'rd' : 'th' :
    +firstDateChar === 1 ?
    'th' :
    +secondDateChar === 1 ? 'st' : +secondDateChar === 2 ? 'nd' : +secondDateChar === 3 ? 'rd' : 'th'
  return `${secondDateChar? +(firstDateChar+secondDateChar) : +firstDateChar}${suffix} ${month}`
}

console.log(getDateRangeList());