最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - List of days between two dates in typescript - Stack Overflow

programmeradmin3浏览0评论

I try to create a list of days between two days.

I created solution like this:

this.daysBetween = [];
while (dateFrom.getDate() !== dateTo.getDate()+1 ) {
    this.daysBetween.push(this.dateFrom);
    dateFrom.setDate(dateFrom.getDate()+1);
  }

But it works only in 90% cases (if there is month change it doesn't work)

e.g. when I pick dates:

dateFrom: 29 august
dateTo: 30 august 

it prints me days from 29 august till 30 september ignoring 31 august ...

Any ideas how to fix my solution, or maybe there is better one?

EDIT:

My question is different than question suggested, because in my question I have as input two dates

e.g.

let dateFrom = new Date(2018, 9, 29);
let dateTo = new Date(2018, 9, 30);

On suggested duplicate result of this could have been int number 1

My question is how to loop through all days between two dates (dateFrom, dateTo)

Where result of those 2 dates examples (dateFrom, dateTo) would've been list with 2 elements:

Mon Oct 29 2018 00:00:00 GMT+0100
Tue Oct 30 2018 00:00:00 GMT+0100 

I try to create a list of days between two days.

I created solution like this:

this.daysBetween = [];
while (dateFrom.getDate() !== dateTo.getDate()+1 ) {
    this.daysBetween.push(this.dateFrom);
    dateFrom.setDate(dateFrom.getDate()+1);
  }

But it works only in 90% cases (if there is month change it doesn't work)

e.g. when I pick dates:

dateFrom: 29 august
dateTo: 30 august 

it prints me days from 29 august till 30 september ignoring 31 august ...

Any ideas how to fix my solution, or maybe there is better one?

EDIT:

My question is different than question suggested, because in my question I have as input two dates

e.g.

let dateFrom = new Date(2018, 9, 29);
let dateTo = new Date(2018, 9, 30);

On suggested duplicate result of this could have been int number 1

My question is how to loop through all days between two dates (dateFrom, dateTo)

Where result of those 2 dates examples (dateFrom, dateTo) would've been list with 2 elements:

Mon Oct 29 2018 00:00:00 GMT+0100
Tue Oct 30 2018 00:00:00 GMT+0100 
Share Improve this question edited Aug 20, 2018 at 8:31 degath asked Aug 20, 2018 at 8:13 degathdegath 1,6215 gold badges37 silver badges63 bronze badges 7
  • 2 Possible duplicate of How do I get the number of days between two dates in JavaScript? – Erik Philips Commented Aug 20, 2018 at 8:17
  • Hello you should have a look to the Date object – Augustin R Commented Aug 20, 2018 at 8:18
  • 1 @ErikPhilips Nope, I dont want to get number of days. I want to loop through those days and also it's typescript here. – degath Commented Aug 20, 2018 at 8:19
  • 1 have you tried using moment? – Jems Commented Aug 20, 2018 at 8:22
  • 1 @ErikPhilips edited question with explanation why it isn't a duplicate. – degath Commented Aug 20, 2018 at 8:31
 |  Show 2 more ments

3 Answers 3

Reset to default 6 Simple Typescript Solution is given below

Javascript version on Github

    class MyDate {
        dates: Date[];
        constructor() {
            this.dates = [];
        }

        private addDays(currentDate) { 
                let date = new Date(currentDate);
                date.setDate(date.getDate() + 1);
                return date;
        }

        getDates(startDate: Date, endDate: Date) { 
            let currentDate: Date = startDate;
            while (currentDate <= endDate) { 
                this.dates.push(currentDate);
                currentDate = this.addDays(currentDate);
            }

            return this.dates;
        }
    }

    let md = new MyDate();
    let daysBetween: Date[] = md.getDates(new Date(2018, 7, 22), new Date(2018, 8, 30));
    console.log(daysBetween);

You could use moment's duration:

/**
 * Get an array of moment instances, each representing a day beween given timestamps.
 * @param {string|Date} from start date 
 * @param {string|Date} to end date
 */
function daysBetween(from, to) {
  const fromDate = moment(new Date(from)).startOf('day');
  const toDate = moment(new Date(to)).endOf('day');

  const span = moment.duration(toDate.diff(fromDate)).asDays();
  const days = [];
  for (let i = 0; i <= span; i++) {
    days.push(moment(fromDate).add(i, 'day').startOf('day'));
  }
  return days;
}

const days = daysBetween('29-Aug-2018', '30-Sep-2018');

console.info(days.map(d => d.toString()).join('\n'));
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.22.2/moment.min.js"></script>

You can alter the loop start/end condition to include/exclude the first/last day.

Update: Using Luxon instead:

const DateTime = luxon.DateTime;

function daysBetween(start,end){
  dateStart = DateTime.fromJSDate(start);
  dateEnd = DateTime.fromJSDate(end);
  
  diffDays = dateEnd.diff(dateStart,'days');
  const days = [];
  for(let i = 0 ; i < diffDays.days; i++){
    days.push(new Date(dateStart.plus({days:i+1}).toMillis()));
  }
  return days;
}


console.log(daysBetween(new Date('23-Feb-2020'),new Date('5-Mar-2020')));
<script src="https://cdn.jsdelivr/npm/[email protected]/build/global/luxon.min.js"></script>

You could calculate the difference in milliseconds, and then convert that into the difference in days.

You can then use this to fill an array with Date objects:

const MS_PER_DAY: number = 1000 x 60 x 60 x 24;
const start: number = dateFrom.getTime();
const end: number = dateTo.getTime();
const daysBetweenDates: number = Math.ceil((end - start) / MS_PER_DAY);

// The days array will contain a Date object for each day between dates (inclusive)
const days: Date[] = Array.from(new Array(daysBetweenDates + 1), 
    (v, i) => new Date(start + (i * MS_PER_DAY)));
发布评论

评论列表(0)

  1. 暂无评论