John Arc
John Arc

Reputation: 183

How to get all the dates within a date range in ionic 3?

I currently have a start date (2019-11-30) and a end date (2019-12-7). How do I list out all the dates in between and put them into an array?

I want to store it in this format in the array:

["2019-11-30", "2019-11-31", "2019-12-1", "2019-12-2", "2019-12-3", "2019-12-4", "2019-11-5"];

Upvotes: 0

Views: 618

Answers (1)

Abdes
Abdes

Reputation: 986

This is a simple example that maybe work for you:

var startDate = new Date("2019-11-30"); //YYYY-MM-DD
var endDate = new Date("2019-12-07"); //YYYY-MM-DD


function formatDate(date) {

  var day = date.getDate();
  var month = date.getMonth()+1;
  var year = date.getFullYear();

  return day + '-' + month + '-' + year;
}

var getDateArray = function(start, end) {
    var arr = new Array();
    var dt = new Date(start);
    while (dt <= end) {
        arr.push(formatDate(new Date(dt)));
        dt.setDate(dt.getDate() + 1);
    }
    return arr;
}

var dateArr = getDateArray(startDate, endDate);

console.log(dateArr)

I hope this will help you

Upvotes: 1

Related Questions