Get a List of Dates Between Two Dates Using JavaScript

Get all Dates between 2 Dates Javascript

you are on the right way

setHours could have an issue with timezone try to use setUTCHours;

and reset start and end dates before any calculations

try out:

function getDatesInRange(startDate, endDate) {
const start = new Date(new Date(startDate).setUTCHours(0, 0, 0, 0));
const end = new Date(new Date(endDate).setUTCHours(0, 0, 0, 0));

const date = new Date(start.getTime());

const dates = [];

while (date <= end) {
dates.push(new Date(date));
date.setDate(date.getDate() + 1);
}

return dates;
}

const travel_start = "2022-03-20T05:59:57.118Z";
const travel_start2 ="2022-03-20T23:59:57.118Z";

const travel_end = "2022-03-23T20:00:57.118Z";

const res1 = getDatesInRange(travel_start, travel_end);
const res2 = getDatesInRange(travel_start2,travel_end);

console.log('res1', res1)
console.log('res2', res2)

How to get the full dates between two dates using javascript / react?

You may calculate the difference between dates, than make up desired array of dates casted to date string of necessary format:

const d1 = new Date('02/20/2020'),      d2 = new Date('03/01/2020'),      diff = (d2-d1)/864e5,      dateFormat = {weekday:'long',month:'short',day:'numeric'},      dates = Array.from(        {length: diff+1},        (_,i) => {          const date = new Date()           date.setDate(d1.getDate()+i)           const [weekdayStr, dateStr] = date.toLocaleDateString('en-US',dateFormat).split(', ')          return `${dateStr} ${weekdayStr}`        }      )      console.log(dates)
.as-console-wrapper {min-height:100%;}

I need to get all the dates between any two dates in JavaScript

You can't simply format javascript date using format function, which doesn't exists. You need to split date, month, year and join. Here it may help-

var startdate = new Date();
var enddate = new Date("2019, 10, 23");

while (startdate < enddate) {
startdate.setDate(startdate.getDate() + 1);
dates.push(startdate.getMonth()+1+"/"+startdate.getDate()+"/"+startdate.getFullYear());
}

You have to increase moth by 1 startdate.getMonth()+1 because month starts from 0 in JS.

Consider using Moment.js which has lots of facility.

Get weekday list between two dates? JavaScript

You can use a for loop to loop through each date between the start and end date, then use Date.getDay to get the day of the week and ignore the dates that are not a weekday.

function getWeekDayList(startDate, endDate) {
let days = []
let end = new Date(endDate)
for (let start = new Date(startDate); start <= end; start.setDate(start.getDate() + 1)) {
let day = start.getDay();
if (day != 6 && day != 0) {
days.push(new Date(start));
}
}
return days;
}

const result = getWeekDayList('2022-01-10', '2022-01-20')

console.log(result.map(e => e.toLocaleString('en-US', {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })))

How to get all dates between two dates given days of the week?

Based on answer of @JohnHartsock we can create the following function which

  • populates range of dates between firstDay and lastDay
  • filter dates based on of daysOfWeek

var days = {Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri:5, Sat:6};
function findClassDays(daysOfWeek, firstDay, lastDay) { let classDays = []; let rangeDates = getDates(new Date(firstDay), new Date(lastDay)); classDays = rangeDates.filter(f => daysOfWeek.some((d, i) => days[d]== f.getDay())); return classDays;}
function getDates(startDate, stopDate) { var dateArray = new Array(); var currentDate = new Date(startDate); while (currentDate <= stopDate) { dateArray.push(new Date (currentDate)); currentDate = currentDate.addDays(1); } return dateArray;}
Date.prototype.addDays = function(days) { var date = new Date(this.valueOf()); date.setDate(date.getDate() + days); return date;}
console.log(findClassDays(['Mon', 'Wed', 'Fri'], '2019-12-01', '2019-12-15'));

Getting list of dates between two dates not returning correctly JS

Try to add new Date(i), instead of just i:

function dateList(dateStart, dateEnd) {  var dates = [];  for (i = dateStart; i <= dateEnd; i.setDate(i.getDate() + 1)){    dates.push(new Date(i));  }  return dates;}
console.log(dateList(new Date('2017-05-08'), new Date('2017-05-12')));

How to enumerate dates between two dates in Moment

.add() is a mutator method, so the assignment in this line is unnecessary:

startDate = startDate.add(1, 'days');

You can just do this, and have the same effect:

startDate.add(1, 'days');

While it's name would imply the creation of a new Date object, the toDate() method really just returns the existing internal Date object.

So, none of your method calls are creating new Date or moment object instances. Fix that by using .clone() to get a new instance:

startDate = startDate.clone().add(1, 'days');

Or better yet, wrap the values in a call to moment() as Mtz suggests in a comment, and it will clone the instance, if the value is a moment object, or it will parse the input to create a new moment instance.

startDate = moment(startDate).add(1, 'days');

I think a date enumerator method should not change either of the arguments passed in. I'd create a separate variable for enumerating. I'd also compare the dates directly, rather than comparing strings:

var enumerateDaysBetweenDates = function(startDate, endDate) {
var dates = [];

var currDate = moment(startDate).startOf('day');
var lastDate = moment(endDate).startOf('day');

while(currDate.add(1, 'days').diff(lastDate) < 0) {
console.log(currDate.toDate());
dates.push(currDate.clone().toDate());
}

return dates;
};


Related Topics



Leave a reply



Submit