The problem you have is that you push references to the date1 object. When you change the date on it in your loop, you update the object, but all references still point to the same object.
You need to either push a text representation of your date, or a copy of your date1 object
for (var i=0; date1 <= date2; date1.setDate(date1.getDate() + 1), i++) {
alldates.push(new Date(date1));
}
alert(alldates.join('\n'));
As suggested, with a while loop
while( date1 <= date2 ) {
alldates.push(new Date(date1));
date1.setDate( date1.getDate() +1 );
}
Answer from jaudette on Stack OverflowThe problem you have is that you push references to the date1 object. When you change the date on it in your loop, you update the object, but all references still point to the same object.
You need to either push a text representation of your date, or a copy of your date1 object
for (var i=0; date1 <= date2; date1.setDate(date1.getDate() + 1), i++) {
alldates.push(new Date(date1));
}
alert(alldates.join('\n'));
As suggested, with a while loop
while( date1 <= date2 ) {
alldates.push(new Date(date1));
date1.setDate( date1.getDate() +1 );
}
Your array is storing the references for the single date object and everytime when setDate is called each of them are getting updated with new date value.
So it will be better to push the new date object in array like this,
var date1 = new Date("Sep 23, 2013 12:00:00"); // Monday
var date2 = new Date("Sep 26, 2013 12:00:00"); // Thursday
var alldates = [];
// pushing first date
alldates.push(new Date(date1.setDate(date1.getDate())));
for (var i=0; date1 <= date2; i++) {
alldates.push(new Date(date1.setDate(date1.getDate() + 1)));
}
alert(alldates.join('\n'));
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(new Date (currentDate));
currentDate = currentDate.addDays(1);
}
return dateArray;
}
Here is a functional demo http://jsfiddle.net/jfhartsock/cM3ZU/
I looked all the ones above. Ended up writing myself. You do not need momentjs for this. A native for loop is enough and makes most sense because a for loop exists to count values in a range.
One Liner:
const getDaysArray = function(s,e) {const a=[];for(const d=new Date(s);d<=new Date(e);d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};
Long Version
const getDaysArray = function(start, end) {
const arr = [];
for(const dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
arr.push(new Date(dt));
}
return arr;
};
List dates in between:
const daylist = getDaysArray(new Date("2018-05-01"),new Date("2018-07-01"));
daylist.map((v)=>v.toISOString().slice(0,10)).join("")
/*
Output:
"2018-05-01
2018-05-02
2018-05-03
...
2018-06-30
2018-07-01"
*/
Days from a past date until now:
const daylist = getDaysArray(new Date("2018-05-01"),new Date());
daylist.map((v)=>v.toISOString().slice(0,10)).join("")
The ES5 spec details the new Date(value) form of the Date constructor. In the algorithm for handling this form, value is converted to a primitive value by calling the [[DefaultValue]] internal method of the object.
Converting an array to a primitive value is basically done by converting the array to a string. Converting an array to a string (Array.prototype.toString) is effectively the same as calling dateArray.join().
Therefore, your call to the Date constructor will effectively look like this:
var dateObject = new Date("2012,6,5");
If the string can be recognised by the Date.parse method, you will end up with a Date instance.
This form of the Date constructor is also listed on MDN as new Date(dateString).
Firefox seems to fail when you pass an array, but it succeeds if you pass the string representation of that array. I would say that that's probably a Firefox bug, but I may be misinterpreting the ES5 spec.
You can use Spread Syntax in ES6.
let dateArray = [2012, 6, 5];
let dateObject = new Date(...dateArray);
console.log('Spread:', dateObject);
console.log('Direct:', new Date(2012, 6, 5));
Hello,
I would like to get the minimum date of this array of objects bellow:
let activities = [
{ title: 'Hiking', date: '2019-06-13' },
{ title: 'Shopping', date: '2019-06-10' },
{ title: 'Trekking', date: '2019-06-22' },
{ title: 'Trekking', date: null }
]
let sortedActivities = activities.sort((a, b) => new Date(a.date) - new Date(b.date))
console.log(sortedActivities[0])The problem is when date activities.date is null it always returns null .
What's the best way to reject null value from this comparison ?
Thanks
Simplest Answer
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
More Generic Answer
array.sort(function(o1,o2){
if (sort_o1_before_o2) return -1;
else if(sort_o1_after_o2) return 1;
else return 0;
});
Or more tersely:
array.sort(function(o1,o2){
return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});
Generic, Powerful Answer
Define a custom non-enumerable sortBy function using a Schwartzian transform on all arrays :
(function(){
if (typeof Object.defineProperty === 'function'){
try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
}
if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;
function sb(f){
for (var i=this.length;i;){
var o = this[--i];
this[i] = [].concat(f.call(o,o,i),o);
}
this.sort(function(a,b){
for (var i=0,len=a.length;i<len;++i){
if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
}
return 0;
});
for (var i=this.length;i;){
this[--i]=this[i][this[i].length-1];
}
return this;
}
})();
Use it like so:
array.sortBy(function(o){ return o.date });
If your date is not directly comparable, make a comparable date out of it, e.g.
array.sortBy(function(o){ return new Date( o.date ) });
You can also use this to sort by multiple criteria if you return an array of values:
// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };
See http://phrogz.net/JS/Array.prototype.sortBy.js for more details.
@Phrogz answers are both great, but here is a great, more concise answer:
array.sort(function(a,b) { return a.getTime() - b.getTime() });
Using the arrow function way
array.sort((a,b) => a.getTime() - b.getTime());
found here: Sort date in Javascript