Javascript - get array of dates between 2 dates
function (startDate, endDate, addFn, interval) {
addFn = addFn || Date.prototype.addDays;
interval = interval || 1;
var retVal = [];
var current = new Date(startDate);
while (current <= endDate) {
retVal.push(new Date(current));
current = addFn.call(current, interval);
}
return retVal;
}
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 do I creating an array of dates between a start and end date?
first of all you can not compare two dates using ==
second problem is you need to create a new Date object each time you push one to the array ex. .push(new Date(q.getTime())
the next problem is you aren't properly adding a day to the last day each time before you push into the array
do something like
pseudo code ---
var dates = [];
while( firstDate < secondDate ){
// this line modifies the original firstDate reference which you want to make the while loop work
firstDate.setDate(firstDate.getDate() + 1);
// this pushes a new date , if you were to push firstDate then you will keep updating every item in the array
dates.push(new Date(firstDate);
}
How can I get array of dates between 2 dates?
You need to increment your fromDate otherwise your while loop will never end. You can use moment to increment your date by one with .add(1,'days')
you are storing the dates in your tempDates, you can log them out after the while loop and then it will contain all your dates in increments of one day.
["2019-12-01", "2019-12-02", "2019-12-03", "2019-12-25", "2019-12-26", "2019-12-29", "2019-12-30", "2019-12-31"]
This will be the contents of your array.
let arr = [
{id:1,fromDate:'2019-06-01',toDate:'2019-06-03'},
{id:2,fromDate:'2019-10-15',toDate:'2019-10-15'},
{id:3,fromDate:'2019-12-01',toDate:'2019-12-03'},
{id:4,fromDate:'2019-12-25',toDate:'2019-12-26'},
{id:5,fromDate:'2019-12-29',toDate:'2019-12-31'}
]
let tempDates = []
arr.forEach(element => {
let now = moment()
let fromDate = moment(element.fromDate)
let toDate = moment(element.toDate)
if (fromDate > now && toDate > now) {
while (fromDate <= toDate) {
let ld = fromDate.format('YYYY-MM-DD')
tempDates.push(ld)
fromDate = moment(fromDate).add(1,'days');
}
}
})
console.log('dates', tempDates);
https://codepen.io/Kaehler/pen/abbYLqX?editors=1010
This should save your array with dates.
your code if (fromDate > now && toDate > now) {
does make the first two objects in the arr array not go into the while loop. You should probably check if fromdate <= toDate
also.
get array of dates between two dates, filtered by dayofweek
You simply can loop from startDate
to endDate
using moment add
and isBefore
.
You can get the day of the week using format('dddd')
.
If you need use toDate()
to convert moment to JavaScript Date
Here a working sample:
function getDateArray(obj){ var start = obj.startDate.clone(); var end = obj.endDate.clone(); var res = []; while(start.isBefore(end)){ var day = start.format('dddd').toLowerCase(); if( obj[day] ){ res.push(start.toDate()); } start.add(1, 'd'); } return res;}
var obj = { startDate: moment(), endDate: moment().add(3, "weeks"), friday: true, monday: true, saturday: false, sunday: false, thursday: false, tuesday: false, wednesday: true};var res = getDateArray(obj);console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
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;
};
How to get array of dates between two dates in laravel?
You can use CarbonPeriod for this.
I found something helpful at https://stackoverflow.com/a/50854594/13642447.
Related Topics
How to Get the Scrollbar Position with JavaScript
Node.Js Plans to Support Import/Export Es6 (Ecmascript 2015) Modules
How to Decode a String with Escaped Unicode
How to Iterate Through Table Rows and Cells in JavaScript
How to Configure Cors in a Spring Boot + Spring Security Application
Why Does [5,6,8,7][1,2] = 8 in JavaScript
How to Move Cursor to End of Contenteditable Entity
Convert JSON Array to an HTML Table in Jquery
How to Compare Software Version Number Using JS? (Only Number)
Warn User Before Leaving Web Page with Unsaved Changes
Getting Value of Select (Dropdown) Before Change
Empty Arrays Seem to Equal True and False at the Same Time
Open a New Tab in the Background
JavaScript Regex Multiline Text Between Two Tags
How to Find Prime Numbers Between 0 - 100