简体   繁体   English

如何在给定日期范围内求和

[英]How to sum values over a given date range

I'm using LocalStorage to save an array of Dates and Costs. 我正在使用LocalStorage保存日期和成本数组。 When I'm writing localStorage.getItem("todos"); 当我写localStorage.getItem("todos"); into the console, the format will be like this: 进入控制台,格式将如下所示:

"[{"due":"28/10/2017","task":"80"},{"due":"06/10/2017","task":"15"}]"

Where due is the Date, and TASK is the AMOUNT. 日期是到期日,任务是金额。

I managed to get the TOTAL of AMOUNTS by: 我设法通过以下方式获得总金额:

total: {
  type: String,
  value: () => {
    var values = localStorage.getItem("todos");
    if (values === undefined || values === null) {
      return "0";
    }
    var data = JSON.parse(values);
    var sum = 0;
    data.forEach(function(ele){ sum+=Number(ele.task)}); return sum;
  }
}

Now I'm trying to get the TOTAL of last 6 MONTHS. 现在,我试图获取最近6个月的总计。 I have no idea on how to approach this. 我不知道如何解决这个问题。 How should I be able to do this? 我应该怎么做?

During your iteration you need to add a check to make sure the sum is only including values where the due date is within your range. 在迭代期间,您需要添加检查以确保总和仅包括到期日期在您的范围内的值。 If you can use a library like moment , this would greatly simplify your logic. 如果您可以使用诸如moment的库,则将大大简化您的逻辑。

 const data = [ { due: '28/10/2017', task: 80 }, { due: '06/10/2017', task: 15 }, { due: '10/05/2000', task: 3000 } ]; const sixMonthsAgo = moment().subtract(6, 'months'); const total = data.reduce((acc, item) => { const dueDate = moment(item.due, 'DD/MM/YYYY'); return acc + (dueDate.isAfter(sixMonthsAgo) ? item.task : 0); }, 0); console.log('total should equal 95: ', total); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script> 

Here is a solution for your issue : make a test in the forEach loop : I've put 4 dates : 2 under 6 months and 2 older The result is 80+15 = 95 这是针对您问题的解决方案:在forEach循环中进行测试:我输入了4个日期:2个低于6个月的日期和2个大日期的结果是80 + 15 = 95

 // After JSON.parse var todos=[{"due":"28/10/2017","task":"80"},{"due":"06/10/2017","task":"15"},{"due":"06/04/2017","task":"15"},{"due":"06/02/2017","task":"15"}]; var sum = 0; var minDate = new Date(); var month = minDate.getMonth()+1-6; // get month minus 6 months var year = minDate.getFullYear(); // get year if(month < 1){ // if month is under January then change year month+=6; year-= 1; } minDate.setMonth(month); // Replace our min date with our - 6 m minDate.setYear(year); // set year in case we have changed todos.forEach(function(ele){ var arr = ele.due.split("/"); // split french string date into d,m,y if(arr.length==3){ var dueDate = new Date(arr[2],arr[1],arr[0]); // get the task date if(dueDate>minDate){ // if task is not to old then sum+=parseInt(ele.task); // sum it } } }); console.log(sum); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM