How to loop through dates using for and while loops - javascript

I would like to be able to loop through an XML file to find the earliest and latest date. Once those dates are found, I want to loop through the records again and compare the month and year from each record to the date that is being passed in. If the month and year match, then the count is increased by one. After the loop goes through all of the records, the date and count are added to an array, the date being passed in is then increased by one, and the loops runs again. The while loop continues to run until the date being increased is greater than the latest record date.
MY CODE:
var record=xmlDoc.getElementsByTagName("record");
var maxDate = 0;
// Loop through all of the records to find the latest date
for(var i=0; i<record.length; i++)
{
var tempMaxDate = record[i].getElementsByTagName("visit_date")[0].childNodes[0].nodeValue;
if(tempMaxDate > maxDate)
{
maxDate = tempMaxDate;
}
}
var minDate = 99999999999999;
// Loop through all of the records to find the earliest date
for(var i=0; i<record.length; i++)
{
var tempMinDate = record[i].getElementsByTagName("visit_date")[0].childNodes[0].nodeValue;
if(tempMinDate < minDate)
{
minDate = tempMinDate;
}
}
var minDateGraph = minDate;
var count = 0;
var data = [];
// Loop until the minimum date is greater than the maximum
while(minDate <= maxDate)
{
var tempMinDate2 = new Date(0);
tempMinDate2.setMilliseconds(minDate);
minDate = tempMinDate2;
// Loop through all of the records
// If the month and year of minDate match the record then the count is increased
for(var i=0; i<record.length; i++)
{
var tempVisitDate = record[i].getElementsByTagName("visit_date")[0].childNodes[0].nodeValue;
var visitDate = new Date(0);
visitDate.setMilliseconds(tempVisitDate);
if((visitDate.getMonth() == minDate.getMonth()) && (visitDate.getFullYear() == minDate.getFullYear()))
{
count += 1;
}
}
var tempData = [minDate, count];
data.push(tempData);
var month = minDate.getMonth();
var year = minDate.getFullYear();
// Increase the minDate by one month
if(month == 12)
{
year += 1;
month = 1;
}
else
{
month += 1;
}
var tempMinDate3 = new Date(year, month, 1).getTime();
minDate = tempMinDate3;
}
The problem is when I run my current code, the browser crashes. I think I am running into an infinite loop, but I cannot find what is causing it. I would appreciate any suggestions. Thanks!

Related

show 2 week in the past ( vue.js)

Hi i have this script ( vue.js ) i can see the next 2 weeks works good i must change that i can see 2 weeks on the past ..
Thanks
methods: {
// Get all days without sunday:
dates(index) {
var week = new Array();
let current = new Date();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 13; i++) {
let date = new Date(current);
week.push(moment(date).format('DD.MM.YY'));
current.setDate(current.getDate() +1);
}
return week[index];
},
If you want to go back in time, you need to subtract from the current date:
methods: {
// Get all days without sunday:
dates(index) {
var week = new Array();
let current = new Date();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 13; i++) {
let date = new Date(current);
week.push(moment(date).format('DD.MM.YY'));
current.setDate(current.getDate() - 1); // <-- this line changed
}
return week[index];
},
Try this:
function dates(index) {
var week = new Array();
let current = moment().subtract(1, 'days');
for (var i = 0; i < 12; i++) {
week.push(current.format('DD.MM.YY'));
current = current.subtract(1, 'days')
}
console.log(week);
return week[index];
}
console.log(dates(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

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

Generate weekdays from today and a week forward

I'm generating divs for each day of the week:
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
var todaysWeekday = days[weekday];
for (var i = weekday; i < days.length; i++) {
$('<div>' + days[i] + '</div>').appendTo('#weekdayList');
}
}
generateWeekdays();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weekdayList"></div>
This generate (for example) today Wednesday and to Saturday (last index), but how can I make it generate one week, so it generates all the way to Wednesday the next week and stops after that?
You can use the module operator % to keep the indexes in bounds. This will make anything beyond the length of the array loop back so you can just go from 0 to the the array length add today's day to it:
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
for (var i = 0; i < days.length; i++) {
console.log(days[(i + weekday) % days.length])
}
}
generateWeekdays()
It's not completely clear in the question but if you want to include next Wednesday, you can loop with for (var i = 0; i < days.length + 1; i++)
Instead of stopping at days.length, you can iterate for 7 (as you want for a week) times, and do a modulo (% 7) operation to get the element from days array.
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
var todaysWeekday = days[weekday];
for (var d = weekday, i = 0; i < 7; d++, i++) {
$('<div>' + days[d % 7] + '</div>').appendTo('#weekdayList');
}
}
generateWeekdays();
How about cutting the days (from normal week days) and appending at the end (those days) for your week (that starts from today's day, you have to cut from there)
function getWeekDaysFromToday() {
let days = ["SUN","MON","TUE","WED","THU","FRI","SAT"];
return days.concat( days.splice (0,new Date().getDay()));
}
console.log(getWeekDaysFromToday())
In your for loop instead of iterating until days.length you want to just do 7 iterations and cycle back to the beginning of the array. If you set up a counter that will iterate 7 times and add an if statement in the loop to loop back to the beginning of the array if you reach the end, that should work.
How about adding another iteration, to take into account of what today is in relation to the index of the array?
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
var todaysWeekday = days[weekday];
for (var i = weekday; i < days.length; i++) {
$('<div>' + days[i] + '</div>').appendTo('#weekdayList');
}
for(var i = 0; i < days.indexOf(days[weekday]); i++){
$('<div>' + days[i] + '</div>').appendTo('#weekdayList');
}
}
generateWeekdays();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weekdayList"></div>
Here is a quick implementation that I threw together. I used a do/while loop because you know you are always going to execute at least once. I Also limit the loop to the number of days you want to display so you could just increment that to show additional days. I also used the % (Modulus) with count and weekday to get the right value from the array.
var days = new Array("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
var todaysWeekday = days[weekday];
let count = 0;
do {
$('<div>' + days[(count + weekday) % days.length] + '</div>').appendTo('#weekdayList');
count++;
} while (count < 7)
}
generateWeekdays()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weekdayList">
</div>
I took a different approach to the question. Rather than checking incrementally if I have processed 7 days, I concatenated the days list to itself, so it would be 14 days, and then starting at the current day, I splice out 7 days so I have a week, and for each of them I create a div.
I also changed it to collect the divs and append them all at the end for some performance gains.
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var oneWeekOfDays = days.concat(days).splice(new Date().getDay(), 7).map(function(day){
return '<div>'+ day +'</div>';
});
$('#weekdayList').append(oneWeekOfDays);
}
generateWeekdays();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weekdayList"></div>
let dataArr = []; //empty array
let days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
let d = new Date();
let weekday = d.getDay(); // it'll return day number like monday is 1
for (var i = 0; i < 7; i++) {
dataArr.push(days[(i + weekday) % days.length]); //push 7 days from today in array
}
console.log(dataArr)

Check if a date is between two dates

I have an array with different dates with the format of year-month-day.
something like this:
var dates = ["2016-08-01", "2016-08-09", "2016-08-10", ....];
I also have a function that formats todays date in the same format as above. And is stored in a variable:
var currentDate; //Contains current date in the format of year-month-day
What i need to do is to check if any of the dates in the array, either:
Match with today's date.- e.g. Today would be 2016-08-13
Match with 14 days back from today's date. - e.g. 14 days back from today (2016-08-13) would be 2016-07-30
Or match with any dates between the current and 14 days back.
I'm trying to do this by looping through the array, checking each value. But im unsure about the if condition/conditions
for(var i = 0; i < dates.length; i++) {
if(currentDate === *condition*) {
sendDate(dates[i]);
}
}
Anyone have a good solution for this? Thanks in advance!
Firstly, create a new Date() from your currentDate ( currentDate is string format Y-d-m with hour and minutes is 00:00)
var current = new Date(currentDate);
var matchWithCurrent = [];
var matchWithDayBack = [];
var between = [];
just loop through your date array
for (var i=0; i<dates.length; i++) {
var tmpDate = new Date(dates[i]); //Convert string to date
var diff = Math.ceil((current - tmpDate) / (1000 * 3600 * 24)); //get time difference (current - tmpDate is milisecond, we need convert it to day)
// Check condition and push it on array correct
if (diff == 0) {
matchWithCurrent.push(dates[i]);
}
if (diff == 14) {
matchWithDayBack.push(dates[i]);
}
if ((diff > 0) && (diff <14)) {
between.push(dates[i]);
}
}
console.log(matchWithCurrent);
console.log(matchWithDayBack);
console.log(between);
If you want only one array match with 3 condition just check 3 condition in only one if and push it into your result array
One way would be to parse the dates to millisecond values and compare them.
var todayParts = currentDate.split('-');
var today = new Date(todayParts[0], todayParts[1], todayParts[2]).getTime();
var otherParts = dates[i].split('-');
var other = new Date(otherParts[0], otherParts[1], otherParts[2]).getTime();
if (today < other + 1209600000 /* 2 weeks in milliseconds */) {
// The other date is less than 2 weeks before today
}
You can read here why I parsed it manually instead of using Date.parse().
You can compare two dates something like that:
var currentDate = new Date();
for(var i = 0; i < dates.length; i++) {<br>
var arrDate = new Date(dates[i]);
if(currentDate == arrDate)
{//compare array dates with current date
//your code here
}
var beforeDate = (currentDate.getDate() - 14); //14 days before
if(arrDate >= beforeDate && arrDate <= currentDate){
//compare dates between current date and 14 days before date
}
}

Javascript to return last 6 months and then use each month as a variable

Hopefully someone can help.
I have the following function to return the last 6 monthly names (I.E June, July, August etc), however, I cannot work out how I would then use each returned month name as separate variables.
I need this so I can feed each month name in to an sql query that populates a table for the last 6 months.
Any help much appreciated.
function getMonths()
{
var today = new Date();
var month = 1;
var currMonth = month-3;
var monthArray = new Array("January","February","March","April","May","June",
"July","August","September","October","November","December");
var menuMonths = new Array();
var count = 6;
var buffer = 10;
while(count >0)
{
if (currMonth < 0)
currMonth += 12;
if (currMonth >=12 )
currMonth -= 12;
var month = monthArray[currMonth];
menuMonths.push(month);
currMonth = currMonth -1;
count = count -1;
}
return (menuMonths.reverse());
}
console.log (getMonths());
You can use Array.slice()
FIDDLE http://jsfiddle.net/BeNdErR/NF5Qm/1/
CODE
var monthArray = new Array("January","February","March","April","May","June",
"July","August","September","October","November","December");
var currMonth = 3; // the current month index, from 1 to 12
var firstMonth = currMonth - 6;
if(firstMonth < 0){ //for example if currMonth is January - 0
var months = [];
months.push(monthArray.slice(12 - Math.abs(firstMonth), 12));
months.push(monthArray.slice(0, currMonth));
alert(months);
}else{
alert(monthArray.slice(firstMonth, currMonth))
}
As output, you still have an array, so you can pass it to the SQL Query as it is, for example (SQLite):
tx.executeSql("SELECT * FROM tablename WHERE month = ? OR month = ? month = ? OR month = ? month = ? OR month = ?;", [slicedMonthArray], successCB, errorCB);
Hope it helps
var months = getMonths();
for(var i=0, len=months.length; i<len; i++){
var currentMonth = months[i];
alert(currentMonth);
//do whatever you want here;
}

Categories

Resources