如何按周Filter()过滤数据数组

时间:2019-04-14 10:22:39

标签: javascript vue.js

当前尝试按周过滤我的数据数组,我已经能够很容易地按天过滤,但是我却在x和y之间的日期(例如按周)上挣扎。

我尝试设置开始日期和结束日期(今天),然后尝试返回小于或等于开始日期和结束日期的日期,但是失败了。

数据数组日期格式:dd / mm / yyyy(01/01/2000)

用户将选择要使用哪个过滤器(因此switch())在7天之前过滤7天。

computed: {
    appointments: function () {

      var today = new Date();
      var dd = String(today.getDate()).padStart(2, '0');
      var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
      var yyyy = today.getFullYear();


      var data = this.$store.state.appointments;

      this.filter1_color = "grey";
      this.filter2_color = "grey";

      switch (this.dateFilter) {
        case 0:
        break;

        case 1:
        console.log("case1: " + today)
        return data.filter(word => word.date == today);

        case 7:

        /// WORKING /// (ex. edit)
        var week = [];

        var today = moment();
        var sevenDaysBefore = today.subtract(7, 'days');

        for (var i = 0; i < data.length; i++) {
          let momentDate = moment(data[i].date, 'DD/MM/YYYY')
          let newDate = momentDate.format("DD/MM/YYYY")
          if (momentDate.isBetween(sevenDaysBefore, moment(), null, '[]')) week.push(data[i]);
        }


        return week
        ///

      }


      return data;
    },

我需要过滤数据以仅显示日期等于过去7天中日期的数组中的项目。

2 个答案:

答案 0 :(得分:3)

您可以使用带有当前日期的moment js库的方法isBetween。您可以使用subtract(7, 'days')减去当前日期的7天。

您可以在一下js库文档中查看有关isBetween方法的更多信息。该方法的第三个参数是粒度,似乎在您的情况下应该为“天”

const today = moment();
const sevenDaysBefore = moment().subtract(7, 'days');

console.log('Today is ' + today.format('MMM Do YYYY'));
console.log('Is ' + today.format('MMM Do YYYY') + ' included in the last seven days?');
console.log(today.isBetween(sevenDaysBefore, today, 'day', '[]'));

console.log('Is ' + sevenDaysBefore.format('MMM Do YYYY') + ' included in the last seven days?');
console.log(sevenDaysBefore.isBetween(sevenDaysBefore, today, 'day', '[]'));

const eightDaysBefore = moment().subtract(8, 'days');
console.log('Is ' + eightDaysBefore.format('MMM Do YYYY') + ' included in the last seven days?');
console.log(eightDaysBefore.isBetween(sevenDaysBefore, today, 'day', '[]'));

const oneDayAfter = moment().add(1, 'days');
console.log('Is ' + oneDayAfter.format('MMM Do YYYY') + ' included in the last seven days?');
console.log(oneDayAfter.isBetween(sevenDaysBefore, today, 'day', '[]'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

答案 1 :(得分:1)

如果您不想或不能使用moment.js之类的库,并且也不必介意具有某些限制的临时实现:

注意

我建议使用一个库来处理Date对象,尤其是在将字符串解析为日期时。手工操作会出错。如果可能,请使用@ f-CJ

的答案

这些部分允许您从字符串创建Date对象。但是,结果Date总是被转换为本地时间,并且字符串需要具有某种格式(您在问题中显示的格式)。如果您需要 UTC支持,则将无法使用。另外,它不能用于解析具有 ISO格式的日期字符串。

const OFFSET_TO_UTC = new Date().getTimezoneOffset();

function parseDateString (dateString, sep) {
  var parts = dateString.split(sep);
  return parts.map(n => Number(n));
}

function localizeDate (pattern, parts) {
  return pattern.reduce((acc, pat, i) => {
    switch (pat) {
      case 'd':
        return Object.assign(acc, { day: parts[i] });
      case 'm':
        return Object.assign(acc, { month: parts[i] });
      case 'y':
        return Object.assign(acc, { year: parts[i] });
      default:
        return acc;
    }
  }, {});
}

function toDate (localized) {
  return new Date(
    localized.year,
    localized.month - 1,
    localized.day,
    0, 0 - OFFSET_TO_UTC, 0);
}

function parseDate (pattern, sep, dateString) {
  return toDate(localizeDate(pattern, parseDateString(dateString, sep)));
}


// try it:

const dStringUS = '04/04/2019'; // mm/dd/yyyy
const dStringDE = '04.04.2019'; // dd/mm/yyyy

const dateUS = parseDate(['m', 'd', 'y'], '/', dStringUS);
const dateDE = parseDate(['d', 'm', 'y'], '.', dStringDE);

console.log(dateUS);
console.log(dateDE);

基于此,您可以编写自己的通用过滤功能:

const OFFSET_TO_UTC = new Date().getTimezoneOffset();

function parseDateString (dateString, sep) {
  var parts = dateString.split(sep);
  return parts.map(n => Number(n));
}

function localizeDate (pattern, parts) {
  return pattern.reduce((acc, pat, i) => {
    switch (pat) {
      case 'd':
        return Object.assign(acc, { day: parts[i] });
      case 'm':
        return Object.assign(acc, { month: parts[i] });
      case 'y':
        return Object.assign(acc, { year: parts[i] });
      default:
        return acc;
    }
  }, {});
}

function toDate (localized) {
  return new Date(
    localized.year,
    localized.month - 1,
    localized.day,
    0, 0 - OFFSET_TO_UTC, 0);
}

function parseDate (pattern, sep, dateString) {
  return toDate(localizeDate(pattern, parseDateString(dateString, sep)));
}



const data = [{
  value: 0,
  date: '04/05/2019'
}, {
  value: 1,
  date: '04/07/2019'
}, {
  value: 2,
  date: '03/07/2019'
}];

function filterByDatePattern (pattern, sep) {
  return function (date, list) {
    return list.filter(item => {
      var itemDate = parseDate(pattern, sep, item.date);
      return itemDate >= date;
    });
  }
}

const onlyUSUntil = filterByDatePattern(['m', 'd', 'y'], '/');
console.log(onlyUSUntil(new Date(2019, 3, 1), data));