Problem with adding dates to an array using the push method: unexpected values being added

Looking to retrieve dates within a specified range

  d = 'Tue Oct 2 00:00:00 UTC+0900 2018';
  date2 = 'Fri Oct 5 00:00:00 UTC+0900 2018';

  var arrTemp = new Array();
  //var dispalyHTML = '';

while(d <= date2){
  //dispalyHTML += d.yyyymmdd();
  var date_yy = d.getFullYear();
  var date_mm = (d.getMonth()+1) < 10 ? '0' +(d.getMonth()+1):(d.getMonth()+1);
  var date_dd = d.getDate() <10 > '0'+d.getDate():d.getDate();

  alert("date_yy+date_mm+date_dd=="+date_yy+date_mm+date_dd);

  **arrTemp.push(date_yy+date_mm+date_dd);**
  d = d.addDays(1);
}


for(j=0; j < arrTemp.length; j++){

    alert("arrTemp[j]=="+arrTemp[j]);
 }

The first set of values represent the target values. Don't dismiss them!

 date_yy+date_mm+date_dd==20181002
 date_yy+date_mm+date_dd==20181003
 date_yy+date_mm+date_dd==20181004
 date_yy+date_mm+date_dd==20181005

However, the values within arrTemp[j] do not match the intended ones.

arrTemp[j]==202802
arrTemp[j]==202803
arrTemp[j]==202804
arrTemp[j]==202805

Curious about the reasons behind this discrepancy?

Answer №1

It's recommended to use the moment library instead of creating your own date functions.

let date1 = moment('02/10/2018', 'DD/MM/YYYY');
let date2 = moment('05/10/2018', 'DD/MM/YYYY');
 
let noOfDays = moment(date2).diff(moment(date1), 'days') + 1;
 
days = (date, noOfDays) => Array.from(Array(noOfDays), (_, i) => moment(date, 'DD/MM/YYYY').add(i, 'd').format('YYYYMMDD'));
 
console.log(days('02/10/2018', noOfDays));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Answer №2

I have made some fixes to the code provided above. It is important to use .toString() when pushing to an array to prevent timestamp values from being added. Please give it a try and let me know how it works for you.

var startDate = new Date('Tue Oct 2 00:00:00 UTC+0900 2018'); 
    var endDate = new Date('Fri Oct 5 00:00:00 UTC+0900 2018');

  var dateArray = [];
  var displayHTML = '';

while(startDate <= endDate){
  var year = startDate.getFullYear();
  var month = (startDate.getMonth()+1) < 10 ? '0' +(startDate.getMonth()+1):(startDate.getMonth()+1);
  var day = startDate.getDate() < 10 ? '0'+startDate.getDate():startDate.getDate();

  console.log("year+month+day=="+year+month+day);
  dateArray.push(year.toString()+month.toString()+day.toString());
  startDate.setDate(startDate.getDate()+1);
}
for(k=0; k < dateArray.length; k++){
    console.log("dateArray[k]=="+dateArray[k]);
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the canvas box's color when you interact with it by clicking inside

I'm in the process of developing a reservation system and I'm looking to implement a feature where the color of a Canvas changes when clicked. The goal is for the color to change back to its original state when clicked again. Snippet from my res ...

A clever way to transfer the "HTML SELECT VALUE" to a different webpage using ajax without the need to refresh the page

Having trouble sending a selected value to another webpage without refreshing? I tried using ajax but couldn't get it to work. After the alert, it seems to stop functioning. Here's the script in one file, where I'm trying to send values 0, 2 ...

Retrieve the most recent record in a MongoDB collection

My goal is to retrieve the last document in a MongoDB collection. In the Mongo shell, I was able to achieve this with the following code: db.collection.find().limit(1).sort({$natural:-1}) This query returns the last object as shown below: { "_id" ...

Parsing a multidimensional JSON array in Java: A step-by-step guide

I have a JSON array object with two dimensions as shown below {"enrollment_data":{"status":"Active","notes":"None","id":"983761"}} To extract the status, notes, and id from the above JSON array object, I have written the following code: JSONParser parse ...

The functionality of Bootstrap Tabs is compromised when used within a jQuery-UI dialog window

My goal is to develop a user interface similar to MDI for my application. To achieve this, I am utilizing the dialog feature of the jQuery UI library. To dynamically create a dialog window on demand, I have coded a helper function as shown below: functio ...

Loading Ajax causes the content to duplicate

My website is created using Wordpress as the CMS with an index featuring a long accordion-style list of post titles. Clicking on a heading loads the content for that post via Ajax onto the index page. However, I am encountering an issue where clicking a h ...

Tips on including various font awesome icons in Vue.js

I am working on designing a section for an app that will feature three tabs, each with its own unique Font Awesome icon. Currently, I have set up the tab structure as shown below, but only one icon is displaying in the tab: <div class="tab"> ...

Is there a method to instruct crawlers to overlook specific sections of a document?

I understand that there are various methods to control the access of crawlers/spiders to documents such as robots.txt, meta tags, link attributes, etc. However, in my particular case, I am looking to exclude only a specific portion of a document. This por ...

Tips on tallying the frequency of items in a state array

I'm currently working on an application in which clicking a button adds the item's value to the state. The button is clickable multiple times, allowing the same item to be added multiple times in the state array. My current code snippet: export ...

Is there a way to fetch database content using ajax prior to triggering a filter keyup event?

I have encountered a challenge with my code below. It currently works when a filter parameter is pressed on keyup. However, I am looking to have the content of the database load via ajax as soon as the page is ready, even without any filter search being in ...

Height and width properties in JQuery not functioning properly on SVG elements in Firefox

I am attempting to create an SVG rectangle around SVG text. I have noticed that when using .width() or .height() on SVG text, Chrome provides the expected results while Firefox does not. Here is a link to a demo I created on jsfiddle. $(document).ready(fu ...

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

Ways to verify the existence of browser sessions when dealing with multiple instances of a browser

In the after Each function, I need to check if browser sessions exist for each instance of the browser being used. If a browser is closed, special tear down logic specific to the app needs to be added by verifying the browser session. ...

What is the ideal solution for resolving the problem of loading HTML page content in this specific situation?

Currently, I am working on an HTML website project where I am integrating header and footer content from separate HTML files into each page using jQuery. However, I have encountered an issue while the page is loading. Upon loading, the content initially ...

The Bootstrap 4 navigation bar fails to be responsive and remains open despite attempts at styling

Having trouble with my navbar functionality... After applying CSS styling, it loses responsiveness and remains open on smaller screens. Here is the code snippet. HTML: <nav class="navbar navbar-expand-sm navbar-dark bg-dark" id="big-bar"> ...

Trying to showcase information received from a server using an API

For a school project, I am developing a website that can retrieve weather data (currently just temperature) based on a city or zip code from openweathermap.org using an asynchronous call. I have successfully retrieved the data from the API, but I am strug ...

Error encountered while saving/loading a multi-dimensional array in C++ to a file

After dedicating approximately 2 weeks to my C++ project, I find myself facing a perplexing issue related to 2D Arrays. To provide some context, here is the current code that I have been working on: http://pastebin.com/vCsz947Q I opted to share this thro ...

Allowing domain access when using axios and express

I have a server.js file where I use Express and run it with node: const express = require("express"); const app = express(), DEFAULT_PORT = 5000 app.set("port", process.env.PORT || DEFAULT_PORT); app.get("/whatever", function (req, r ...

Controlled Checkbox Component in React

I'm really struggling with this. While I can easily work with select drop downs and text fields, I just can't seem to get checkboxes to function properly in a controlled manner. I want them to 'toggle' and respond to events in a parent ...

"How to change the hover background of a select element in Chrome from its default setting to something else

https://i.sstatic.net/G2deM.png Is there a way to remove the background color on hover and replace it with a different color? .drp-policydetails { border: 1px solid #dddddd; background-color: #ffffff; } <div className="form-group"> <sele ...