Moment.js while loop in javascript, node.js - javascript

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>

Related

Moment not returning date range

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;
};

convert date to number in javascript

I'm using google app script for some application and in javascript m getting NaN error
var state = $("#state").text();
var now = new Date();
var startDate = $("#startDate").val();
var endDate = $("#endDate").val();
var sdate=Number(startDate);
var edate=Number(endDate);
var empName = $("#searchEmpName").val();
alert(edate+","+sdate);
if (edate < sdate){
// show error msg
}
You can use var sdate = parseInt(startDate); instead of var sdate = Number(startDate); and same for the end date.
var sdate=new Date(startDate);
var edate=new Date(endDate);
Here no need to convert sdate and edate in Number.
You can compare both the dates now as you have done before.

How to return an array of all the dates between two selected dates using javascript

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);

How to get new array between selected two dates using javascript array

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);

is Javascript array.push method synchronous?

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/

Categories

Resources