【问题标题】:How to get list of months between 2 years in typescript for angular如何在 Angular 的打字稿中获取 2 年之间的月份列表
【发布时间】:2022-02-16 23:38:57
【问题描述】:

我有一个来自日期选择器的 fromDate 和 toDate - 假设 fromDate 是 2021 年 9 月 5 日,而 toDate 是 2022 年 2 月 2 日,我需要两者之间缺失月份的列表。我最初尝试使用 moment.js 并使用 arr.reduce 和 arr.findIndex 函数。但没有得到预期的输出。请帮忙。

例如。

var arr = [
  {month: 7,  year: 2021, count: 21},
  {month: 12, year: 2021, count: 54},
  {month: 2,  year: 2022, count: 76}
];

预期 o/p =

[
  {month: 7,  year: 2021, count: 21}, 
  {month: 8,  year: 2021, count: 0},
  {month: 9,  year: 2021, count: 0},
  {month: 10, year: 2021, count: 0},
  {month: 11, year: 2021, count: 0},
  {month: 12, year: 2021, count: 54},
  {month: 1,  year: 2022, count: 0},
  {month: 2,  year: 2022, count: 76}
];

【问题讨论】:

  • 是的,即使是要包含在预期的操作中
  • 这能回答你的问题吗? JavaScript: get all months between two dates?
  • 为什么源数组有 3 个项目?不仅仅是fromto 日期?
  • @AlexandrBelan 因为也有计数。看起来他想保留这些。

标签: javascript arrays angular typescript datetime


【解决方案1】:

一种方法是将年份和月份视为一个值。 例如。 var ym = year * 12 + (month - 1)

如果这样做,则可以将 YM 值与数组中的下一项进行比较,如果低于,则可以在它们之间的数组中插入一个新项。

更新,添加了两个实用函数,使这更容易,YM,基本上会将年/月转换为线性数字,然后 RYM 会将这个数字转换回{year, month},奖金,我认为它使代码更容易也跟着去。

下面是一个例子..

var arr = [
  {month: 7,  year: 2021, count: 21},
  {month: 12, year: 2021, count: 54},
  {month: 2,  year: 2022, count: 76}
];

/*var arr = [
  {month: 11, year: 2021, count: 54}, 
  {month: 2, year: 2022, count: 76} 
]; */

const YM = ({year, month}) => year * 12 + month - 1;

const RYM = ym => ({
   year: Math.trunc(ym / 12), 
   month: (ym % 12) + 1
});


function fillSpace(arr) {
  let st = 0;
  while (st < arr.length -1){
    const thisYM = YM(arr[st]);
    const nextYM = YM(arr[st + 1]);
    if (thisYM + 1 < nextYM) 
      arr.splice(st + 1, 0, {
        ...RYM(thisYM + 1),
        count: 0
      });     
    st += 1;
  }
}

fillSpace(arr);

console.log(arr);

【讨论】:

  • 感谢 Keith,这里假设数组中只有 2 个对象,例如 - 让 arr = [{month: 11, year: 2021, count: 54}, {month: 2, year: 2022, count: 76} , 12 个月未显示..
  • @arv 啊,是的,.. 忘记月份是基于 1,而不是基于 0.. :),打勾,我会更新
【解决方案2】:

新日期(新日期(d2) - 新日期(d1)).getMonth();

【讨论】:

  • 您提出的响应并没有解决该语句。
  • 对不起。不过谢谢。
猜你喜欢
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
相关资源
最近更新 更多