我如何从当前日期开始的数组中获取7个连续的日期(数组中的日期不同)?

时间:2019-03-07 09:34:32

标签: javascript arrays node.js

可以说我的当前日期是“ 5月9日”,现在我希望在“ 5月9日”之后获得7个连续事件(日期)。这是我的json数组示例

[{
    "date": "4 Mar",
    "day": "Mon",
    "holiday_name": "bbb"
},
{
    "date": "7 Mar",
    "day": "Thu",
    "holiday_name": "ccc"
},
{
    "date": "8 Mar",
    "day": "Fri",
    "holiday_name": "ddd"
},
{
    "date": "5 Apr",
    "day": "Fri",
    "holiday_name": "eee"
},
{
    "date": "14 Apr",
    "day": "Sun",
    "holiday_name": "fff"
},
{
    "date": "14 Apr",
    "day": "Sun",
    "holiday_name": "gfgg"
},
{
    "date": "24 Apr",
    "day": "Wed",
    "holiday_name": "ttt"
}, ...
//more in the list]

我得到了当前日期,

let day = date.getDate(); const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; let month = monthNames[date.getMonth()]; let appendDate = day + " " + month;

1 个答案:

答案 0 :(得分:3)

首先,您可以按日期的升序对数组进行排序。然后使用filter获得日期大于或等于所需日期的新数组。您的情况是May 9,在下面的示例中,我考虑了今天的日期。之后,您可以使用slice获得所需的天数。在您的情况下为9,但例如,我考虑了2

let date = [{
    "date": "3 Mar",
    "day": "Mon",
    "holiday_name": "bbb"
  }, {
    "date": "4 Mar",
    "day": "Mon",
    "holiday_name": "bbb"
  },
  {
    "date": "7 Mar",
    "day": "Thu",
    "holiday_name": "ccc"
  },
  {
    "date": "8 Mar",
    "day": "Fri",
    "holiday_name": "ddd"
  },
  {
    "date": "5 Apr",
    "day": "Fri",
    "holiday_name": "eee"
  },
  {
    "date": "14 Apr",
    "day": "Sun",
    "holiday_name": "fff"
  },
  {
    "date": "14 Apr",
    "day": "Sun",
    "holiday_name": "gfgg"
  },
  {
    "date": "24 Apr",
    "day": "Wed",
    "holiday_name": "ttt"
  }
];

let dt = date.sort(function(a, b) {
  return new Date(a.date) - new Date(b.date)
});

function getConsDate(dat) {
  return dt.filter(function(item) {
    return new Date(item.date) >= new Date(dat)
  }).slice(0, 2)
}

console.log(getConsDate('7 March'))