Finding the complete list of dates within a range using JavaScript/React

I am trying to find the number of days between two dates.

For instance, if the start date is 02/20/2020 and the end date is 01/03/2020, I want to display the result like:

Feb 20 Thursday, Feb 21 Friday,..., Jan 3 Monday.

I have searched for a solution on StackOverflow, but unfortunately, I did not find one that met my expectations.

Can someone please help me achieve this using JavaScript or React?

Answer №1

To find the difference between two dates, you can create an array of dates in the desired format:

const startDate = new Date('02/20/2020'),
      endDate = new Date('03/01/2020'),
      difference = (endDate - startDate) / 864e5,
      dateFormat = {weekday:'long', month:'short', day:'numeric'},
      datesArray = Array.from(
        {length: difference + 1},
        (_, index) => {
          const currentDate = new Date();
          currentDate.setDate(startDate.getDate() + index);
          const [weekdayString, dateString] = currentDate.toLocaleDateString('en-US', dateFormat).split(', ');
          return `${dateString} ${weekdayString}`;
        }
      )
      
console.log(datesArray)
.as-console-wrapper {min-height:100%;}

For a fun diversion, here's a React implementation:

const { render } = ReactDOM,
      { useState } = React;
      
const DatePicker = ({ min, max, onPick }) => (
  <input 
    type="date" 
    onChange={onPick}
    {...{min,max}}
  />
);  

const ListOfDates = ({ startDate, endDate }) => {
    const firstDate = new Date(startDate),
          lastDate = new Date(endDate),
          difference = (lastDate - firstDate) / 864e5,
          dateFormat = { weekday: 'long', month: 'short', day: 'numeric' },
          datesList = Array.from(
            { length: difference + 1 },
            (_, index) => {
              const date = new Date(); 
              date.setDate(firstDate.getDate() + index); 
              const [weekdayStr, dateStr] = date.toLocaleDateString('en-US', dateFormat).split(', '); 
              return `${dateStr} ${weekdayStr}`; 
            }
          );
     return (
        <ul>
          {datesList.map((dateItem, key) => <li key={key}>{dateItem}</li>)}
        </ul>
     );
};

const App = () => {
  const [start, setStart] = useState(''),
        [end, setEnd] = useState(''),
        chooseStartDate = ({ target: { value } }) => setStart(value),
        chooseEndDate = ({ target: { value } }) => setEnd(value);
  return <>
    <DatePicker max={end} onPick={chooseStartDate} />
    <DatePicker min={start} onPick={chooseEndDate} />
    <ListOfDates startDate={start} endDate={end} />
  </>
};

render (
  <App />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

And here's how it can be done with jQuery:

$(document).ready(() => {
  $('.datepick').on('change', function(){
    $(this).attr('id') == 'startDate' ?
    $('#endDate').attr('min', $(this).val()) :
    $('#startDate').attr('max', $(this).val());
    if ($('#startDate').length && $('#endDate').length) {
      const initialDate = new Date($('#startDate').val()),
            finalDate = new Date($('#endDate').val()),
            daysDifference = (finalDate - initialDate) / 864e5,
            format = { weekday: 'long', month: 'short', day: 'numeric' },
            datesArray = Array.from(
              { length: daysDifference + 1 },
              (_, index) => {
                const currentDate = new Date(); 
                currentDate.setDate(initialDate.getDate() + index); 
                const [dayOfWeek, specificDate] = currentDate.toLocaleDateString('en-US', format).split(', '); 
                return `${specificDate} ${dayOfWeek}`; 
              }
            ),
            dateItems = datesArray.map(date => `<li>${date}</li>`); 
            $('#dateList').html(dateItems)
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Start Date: <input id="startDate" type="date" class="datepick"></input></label>
<label>End Date: <input id="endDate" type="date" class="datepick"></input></label>
<ul id="dateList"></ul>

Answer №2

One way to achieve this is by utilizing the momentjs library:


<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//let moment = require("moment");

let date = [];

let startDate = "02/20/2020";
let endDate = "01/03/2020";
while ( moment(startDate, "MM/DD/YYYY").valueOf() <= moment(endDate, "DD/MM/YYYY").valueOf()) {
  date.push(moment(startDate, "MM/DD/YYYY").format("MMM DD dddd"));
  startDate = moment(startDate, "MM/DD/YYYY").add(1, "days").format("MM/DD/YYYY");
}
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Answer №3

To begin, create two date objects representing the start and end dates. Calculate the number of days between these dates and iterate through that range to print each date.

Here's a sample code snippet for a React component:

const App = () => {
  const [dates, setDates] = React.useState([]);

  React.useEffect(() => {
    const start = new Date('02/20/2020');
    const end = new Date('03/01/2020');

    const daysBetween = (end.getTime() - start.getTime()) / (1000 * 3600 * 24);
    const arr = [];

    for (let i = 0; i <= daysBetween; i++) {
      const temp = new Date();
      temp.setDate(start.getDate() + i)
      arr.push(temp);
    }
    
    setDates(arr);
  }, []);
  
  return (
    <ul>
      {dates.map(date => (
        <li key={date}>
          {date.toLocaleDateString(
            "en-US",
            {month: "short", day: "2-digit", weekday: "long"}
          )}
        </li>
      ))}
    </ul>
  );
}

ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Answer №4

To find the difference in days from the given date, one can calculate the number of days and then use a loop to log each day incrementally between the start and end dates using toLocaleString().

const startDate = "02/20/2020";
const endDate = "03/01/2020";

const diffTime = Math.abs(new Date(endDate) - new Date(startDate));
const diffDays = 0|diffTime/864e5; 


for(let i = 0; i <= diffDays; i++){
  const newdate = new Date(new Date(startDate).getTime()+(i*864e5));
  console.log(newdate.toLocaleString('en-us', { day:'2-digit', month: 'short', weekday:'long'}))
}

Answer №5

If you're looking for another way to find the difference between two dates using JavaScript, try this method:

const startDate = new Date("06/30/2019"); 
const endDate = new Date("07/30/2019"); 

// Calculate the time difference between the two dates 
const timeDifference = endDate.getTime() - startDate.getTime(); 

// Calculate the number of days between the dates 
const numberOfDays = timeDifference / (1000 * 3600 * 24); 

while (numberOfDays !== 0) {
    let date = new Date(endDate);
    date.setDate(date.getDate() - numberOfDays);
    console.log(date);
    numberOfDays--;
}

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

Navigating Parent Menus While Submenus are Expanded in React Using Material-UI

My React application includes a dynamic menu component created with Material-UI (@mui) that supports nested menus and submenus. I'm aiming to achieve a specific behavior where users can access other menus (such as parent menus) while keeping a submenu ...

Uploading Files in HTML

My goal is to create a way to input a file using the following method: Input file: <input type="file" name="-f" id="fa"> I would like to include an HTML link (upload example) that, when clicked, will upload an example file without opening the file ...

Organize array by "categories" in Javascript and preserve the original sequence

There is a dataset presented below: [ { "name": "Item1", "section": "section1", "total": 3, }, { "name": "Item1", "section": "section2", "total": 4, }{ "name": "Item1", "section": "section3", "total": 7, }, { "name" ...

Tips on showing a success notification following form submission in HTML

I have crafted this code utilizing a combination of bootstrap, python, and html. I have omitted the css portion for brevity, but I can certainly provide it if necessary. My aim is to be able to send an email using smtplib and flask, with the added function ...

Error Timeout Encountered by Langchain UnstructuredDirectoryLoader

I am facing an issue while trying to load a complex PDF file with tables and figures, spanning approximately 600 pages. When utilizing the fast option in Langchain-JS with NextJS Unstructured API, it partially works but misses out on some crucial data. On ...

Remove any javascript code from the ajax modal when it is closed or hidden

I am in the process of creating a music website that showcases songs along with their lyrics. One of the features I have added is a lyrics button that, when clicked while a song is playing, opens up a modal displaying the live lyrics. Everything works per ...

Is it necessary for an element in BEM to be contained within a block?

I have a question about BEM methodology. Is it acceptable to use a .block__element class on its own without a parent block? I am working on a WordPress site with various classes from the theme, page builder, and plugins, which can make things messy when tr ...

How can jQuery be referenced?

Is there a way to adjust the jQuery code that targets the elements above within the HTML? The HTML code looks like this: <div class="dramer"> <ul> <li> </li> <li> <a class="shares" href="#"> Click & ...

Is it possible to make an element draggable after it has been prep

Seeking assistance with making a notification draggable when added to a webpage. The notifications are housed in a parent div named notification_holder Here is the structure: <div class="notification_holder"> <div class="container"><b ...

Enhancing table field functionality in Backbone.js

In my Backbone application, I am trying to debug the following code outline. window.TableView = Backbone.View.extend({ initialize: function() {... .. .. ... }); }, selectRow: function() { ... ... .. }, render: function() { // ...

Choose the Enum in a dynamic manner

I have three enums Country_INDIA, Country_USA,Country_AUSTRALIA. During runtime, the specific country name is determined (it could be either INDIA, USA, or AUSTRALIA). Is it possible to select the correct enum based on the country name at runtime? For in ...

Why is the value of the form's select element always null in jQuery?

I have completed this task multiple times without any issues, but I seem to be facing a problem now. Whenever I make a selection from the dropdown list, the .value always returns null, which is puzzling as I know this should not be the case. Can anyone spo ...

Looking to include a new item into an array with the help of AngularJS

Having just started with angularJS, I am facing difficulties in adding an object from a form to an array. When I click on "Add New Product", it triggers the "newItemModal". I enter the new product information but the submit button doesn't seem to work ...

Setting a variable within an ng-repeat using ng-click

Struggling to create a pagination system and encountering issues with updating the CurrentPage Variable. When trying to update it using <li ng-click="currentPage"...., the variable does not update. Here is the problematic fragment: http://jsfiddle.net/f ...

Ways to activate a special function after clicking a social media button?

My goal is to implement a social media div locker on my website. The concept involves hiding a piece of text behind a div locker that prompts the user to share the content on Facebook, Google+, or Twitter in order to unlock it. After the visitor clicks on ...

Failure to register Express Route

I am currently using express and facing some challenges with creating routes using express.Router. Below is my index.js file (npm main file): require('dotenv').config() const express = require('express') const loaders = require('. ...

What is the best way to ensure an input field and a button are aligned perfectly within the same div tag and of equal height?

During a recent HTML-CSS project, I encountered an issue where I struggled to ensure that two elements within a div tag were the same height. The elements in question were an input field and a button with an icon. Here is a snippet of the relevant HTML cod ...

The ngModel controller did not trigger the $$updateEventHandler function

Currently in the process of transitioning the development environment from gulp to webpack for a hybrid app that does not use AngularJS and React. The application is quite large, currently consisting of 10mb worth of files. However, I have encountered an ...

Developing a dynamic slideshow using jQuery

I'm working on a website where I want an image to change when I click on a specific piece of text. Currently, I have set up a class called "device" with one of them having the class "active" like this: <div class="col-md-3"> <div c ...

Deleting a script from a database using jQuery AJAX

I'm attempting to remove files from my database via an AJAX call, however, I seem to be missing a step. Instead of displaying "del id", I only see * del".$row1['id']." *. Can anyone assist me with this issue? // Here is the main file // &l ...