My javascript array like that. var datearray = ["2010-01-10","2010-01-20","2014-01-35","2014-10-22","2014-03-02","2010-02-11","2010-03-18","2010-09-09","2014-11-12","2014-02-23","2014-03-02","2014-03-02","2014-04-22","2014-05-09","2014-02-23","","2010-02-19","2010-03-01","2010-02-27","2010-02-25"];
but my searching dates are startDate = 2010-01-01; and endDate = 2010-03-29; I want to get new date array between above startDate and endDate; How I created It.
var dateArray = ["2010-01-10","2010-01-20","2014-01-35","2014-10-22","2014-03-02","2010-02-11","2010-03-18","2010-09-09","2014-11-12","2014-02-23","2014-03-02","2014-03-02","2014-04-22","2014-05-09","2014-02-23","","2010-02-19","2010-03-01","2010-02-27","2010-02-25"],
startDate = Date.parse("2010-01-01"),
endDate = Date.parse("2010-03-29");
var filteredDateArray = dateArray.filter(function(s) {
s = Date.parse(s);
return s > startDate && s < endDate;
});
console.log(filteredDateArray);
Related
I am trying to create a date array between 2 dates.
[11/16/2018, 12/16/2018, 1/16/2019......11/16/2019]
I have the following code.
function dateRange(stDate, etDate) {
const dates = [];
var startDate = moment(new Date(stDate)).format("MM/DD/YYYY");
var endDate = moment(new Date(etDate)).format("MM/DD/YYYY");
var now = new Date(startDate);
while (startDate <= endDate) {
dates.push(new Date(now));
now = now.addMonths(1);
}
console.log("dateRange " + dates);
}
function RunLedgerAndPV() {
var stDate = "11/16/2018";
var etDate = "11/16/2019";
dateRange(stDate, etDate);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Trying to debug it, it doesn't break or anything and it is returning the just the start and end date but doesn't push the date array. What am i doing wrong here?
Also, i have looked at the other posts regarding this and i have myself worked on date range in the past. However, i am clueless as to why this isn't working for me.
Any help is appreciated. Thank you!
There are quite a few inefficiencies and bugs in your code, too many to list really. A summary would include unnecessary creation and then re-stringifying of dates, unnecessary use of JS Date constructors and dodgy logic in your for loop.
Here's a version which will work correctly using just momentJS functionality:
function createLedger(stDate, etDate) {
if (stDate && etDate) {
var endOfLeaseDate = moment(etDate, "MM/DD/YYYY");
var startOfLeaseDate = moment(stDate, "MM/DD/YYYY");
dateRange(startOfLeaseDate, endOfLeaseDate);
}
}
function dateRange(stDate, etDate) {
var dates = [];
var now = stDate.clone();
var day = stDate.date();
while(now.isBefore(etDate)) {
//deal with variable month end days
var monthEnd = now.clone().endOf("month");
if (now.date() < day && day <= monthEnd.date()) { now.date(day); }
dates.push(now.format("YYYY-MM-DD"));
now = now.clone().add({ "months" : 1 });
}
console.log(dates);
}
function RunLedgerAndPV() {
var stDate = "12/31/2018";
var etDate = "12/31/2019";
createLedger(stDate, etDate);
}
RunLedgerAndPV();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
for (var i=0; now <= endDate; i++) {
dates.push(new Date(now));
now = now.addMonths(1);
}
you instantiate and use i in order to loop through nothing. the condition now <= endDate is in no way affected by the value of i ( typically you increment / decrement i until it reaches the desired value as : var i=0; i < 11; i++ ) i dont event know how this would work, my first instinct is that it will generate a loop that wont stop until until we reach that endDate date.
You seems to be looking for getting all the date between a specific range, try the following :
var enumerateDaysBetweenDates = function(startDate, endDate) {
var dates = [];
var currDate = moment(startDate, 'MM/DD/YYYY');;
var lastDate = moment(endDate, 'MM/DD/YYYY');;
while(currDate.add(1, 'months').diff(lastDate) < 0) {
console.log(currDate.toDate());
dates.push(currDate.clone().toDate());
}
return dates;
};
The code supposes to fill the array with dates between given start and end dates. I am using Node.js.
var startDate = moment(startDay);
var endDate = moment(endDay);
var datesBetween = [];
var startingMoment = startDate;
while(startingMoment <= endDate) {
datesBetween.push(startingMoment);
startingMoment.add(1, 'days');
}
console.log(datesBetween);
You need to create a new object each iteration otherwise you are pushing the same object reference into array each time. They will all end up with last date since it is all the same object
You can use moment.clone() to clone the object each time
var startDay = new Date(2018,1,1);
var endDay = new Date(2018,1,4);
var startDate = moment(startDay);
var endDate = moment(endDay);
var datesBetween = [];
var startingMoment = startDate;
while(startingMoment <= endDate) {
datesBetween.push(startingMoment.clone());// clone to add new object
startingMoment.add(1, 'days');
}
console.log(datesBetween);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"></script>
For my class assignment, I need to return an array of dates in between two selected dates on a calendar (arrival & departure).
I was given two sets of code that I can use, however I can't figure out how to link them together.
var arrival = document.getElementById('arrivalDate');
console.log(arrival.value);
var checkout = document.getElementById('departureDate');
console.log(checkout.value);
// Figure out the number of days they are check in for.
var days = checkout.value.split('-')[2] - arrival.value.split('-')[2];
console.log(days);
function dateRange(arrival, days) {
range = [];
// Starting At
return range;
}
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2013,10,22), new Date(2013,11,25));
dates.forEach(function(date) {
console.log(date);
});
Seems pretty simple when you've already been given the answer!
var arrivalDate = new Date(document.getElementById('arrivalDate').value);
var departureDate = new Date(document.getElementById('departureDate').value);
var dateRange = getDates(arrivalDate, departureDate);
I am writing a simple javascript function but it is not as I have expected.
The following is the code:
var startDate = new Date('2015-07-01 00:00 +0800');
var endDate = new Date('2015-07-10 00:00 +0800');
var arrayOfDates = [];
if (endDate >= startDate) {
while (startDate < endDate) {
arrayOfDates.push(startDate);
startDate = new Date(startDate.setDate(startDate.getDate() + 1));
}
}
While I am expecting the result of arrayOfDates to be [2015-07-01, 2015-07-02, 2015-07-03.... , 2015-07-10']. The results is instead [2015-07-02, 2015-07-03.... , 2015-07-10']
Why is that? Is it somehow the var startDate is updated before the variable is pushed to the array? if that's the case how can I make sure the code is running synchronously?
When you call setDate(), that changes the date. All the setter functions on the Date prototype mutate the date instance.
You have to make a new date instance and then subsequently call the setter to change it.
startDate = new Date(startDate);
startDate.setDate(startDate().getDate() + 1);
It will do job for you and it wont change your date untill your current date is pushed:
var startDate = new Date('2015-07-01 00:00');
var endDate = new Date('2015-07-10 00:00');
var arrayOfDates = [];
if (endDate >= startDate) {
for(var dt = startDate; startDate < endDate; dt = new Date(startDate.setDate(startDate.getDate() + 1))){
console.log(startDate);
arrayOfDates.push(startDate);
}
}
Here you have fiddle https://jsfiddle.net/ggqzbn6h/
I want to filter using date but the data is in JSON format. How can I filter the large dataset using date in JavaScript?
Example:
data=[{date:'22-12-2014',name:'selva'},{date:'10-10-2010',name:'raja'},{date:'11-11- 2011',name:'suresh'}]
If you simply want to filter data by time, you can look through all objects in the array like this:
var filteredData = [];
for(var index in data) {
var obj = data[index];
var date = parseDate(obj.date);
//Filter dates from 2011 and newer
if(date > new Date(2011, 0, 1))
filteredData.push(obj);
}
function parseDate(dateStr) {
var date = dateStr.split('-');
var day = date[0];
var month = date[1] - 1; //January = 0
var year = date[2];
return new Date(year, month, day);
}
//Filtered data now contains:
// [{"date":"22-12-2014","name":"selva"},{"date":"11-11- 2011","name":"suresh"}]
I am sure you could do the parse date better, by for example defining the date in a format that the Date constructor accepts.
To grab the set of elements that match a certain date you can use filter to extract them into a new array.
function getByDate(date){
return data.filter(function (el) {
return el.date == date;
});
}
var arr = getByDate('11-11-2011');
To to sort your dataset by date you need to convert your date strings to a JS date object first. That involves adjusting the date string slightly so it can be parsed properly.
function reformatDate(date) {
return arr = date.split('-').reverse();
}
var sortByDate = function (a, b) {
return new Date(reformatDate(a.date)) - new Date(reformatDate(b.date));
};
data.sort(sortByDate);
JSFiddle demo
I used date format MM/DD/YY. Here is the full example -
var data=[
{date:'02/10/2018',name:'date is 10'},
{date:'02/14/2018',name:'date is 14'},
{date:'02/16/2018',name:'date is 16'},
{date:'02/20/2018',name:'date is 20'},
{date:'02/24/2018',name:'date is 24'},
{date:'02/26/2018',name:'date is 26'},
{date:'02/30/2018',name:'date is 30'},
{date:'03/01/2018',name:'date is 01'},
{date:'03/05/2018',name:'date is 05'},
{date:'02/23/2018',name:'date is name 23'},
]
var today = new Date();
var todayTime = new Date().getTime();
var days_after_20 = new Date().setDate(today.getDate()+20);
var days_before_5 = new Date().setDate(today.getDate()-5);
var result = data.filter(function (item) {
var itemTime = new Date(item.date).getTime()
return itemTime >= days_before_5 && itemTime <= days_after_20;
})
console.log(result);
To fetch the set of elements that match a certain date you can use filter to extract them into a new array.
var tempArray= data.filter(function (d, i) {
return d >= startDate && d <= endDate;
})