从开始日期和结束日期获取中间日期

时间:2021-02-11 07:40:31

标签: angular typescript

我最初是通过类似的东西来工作的

var x = endDay - startDay;

for(//iterate for x)  
{
  if(startMonth = endMonth){
     //Push items to array
  }
}

然后我意识到,如果我从 2021 年 12 月 28 日到 2022 年 1 月 4 日之间取一个日期是行不通的。

所以我会展示我的代码,但通常这更多是一个逻辑问题,然后实际代码不起作用..

  createSpecial(startDate, endDate){

  
    var startValue = startDate.split("/");
    var startDay = startValue[0];
    var startMonth = startValue[1];
    var startYear = startValue[2];
   
    var endValue = endDate.split("/");
    var endDay = endValue[0];
    var endMonth = endValue[1];
    var endYear = endValue[2];


    var diff = parseInt(endDay) - parseInt(startDay);
    let difference: Range[] = [];
    var startdate: string = startDay.toString();
    
    for (let i = 0; i <= diff; i++) {
     
        var x = parseInt(startdate);
        x++;
        var s = startdate.toString();
        s = s.padStart(2, '0');
        startdate = x.toString();
        difference.push({
          day: s,
          month: startMonth,
        });
    }
    
export class range{
  day: string;
  month: string;

}

现在我非常不清楚如何解决这个问题,如何从 startDate 和 endDate 获取值以用于迭代并创建介于两者之间的范围以供以后使用。

我基本上只需要获得开始和结束之间的天数,我会弄清楚如何迭代到下个月的后记

编辑:评论向我指出了另一个问题,它为我回答了这个问题: https://stackoverflow.com/questions/4413590/javascript-get-array-of-dates-between-2-dates#:~:text=Try%20this%2C-,remember,-to%20include%20moment

4 个答案:

答案 0 :(得分:1)

如果你只需要这两天之间的天数,你可以简单地做:

let t1 = start.getTime()
let t2 = end.getTime()

let numberOfDaysBetween = (t2 - t1) / 86400000

答案 1 :(得分:1)

使用 Date 类型

function getDayDiff(a, b) {
    return Math.abs(a.getTime() - b.getTime()) / (1000 * 60 * 60 * 24)/*1d in ms*/;
}
getDayDiff(new Date(2020, 0), new Date(2021, 0)); // 366

答案 2 :(得分:0)

你可以尝试下一个。使用 Date 对象作为日期

function monthDiff(firstDate, secondDate) {
let months;
months = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
months -= firstDate.getMonth() + 1;
months += secondDate.getMonth();
return months <= 0 ? 0 : months;
}

答案 3 :(得分:0)

为什么不使用 date-fns ? 与 moment 不同的是,它不会使您的尺寸预算爆炸。它只是导入您将要使用的函数。

npm i date-fns@2.16.1 --save

然后

import { addDays, eachDayOfInterval } from "date-fns";
let dates = eachDayOfInterval(
      {
        start: new Date(),
        end: addDays(new Date(), 10)
      },
      { step: 1 }
    );
  }