4

My requirement is to get the number of days between two dates.

For example, the start date is 02/20/2020 to 01/03/2020 I would like to display the results like

Feb 20 Thursday, Feb 21 Friday,....01 Mar Monday.

I went through this scenario in StackOverflow but I didn't get the expected solution for the same.

Could anyone please guide in achieving this scenario using javascript or react?

John_ny
  • 767
  • 12
  • 33
  • I've reopened this as OP wants to print the full dates between the start and end date. The duplicate target only showed how to get the number of days between two dates, not how to print each of them. – Chris Feb 20 '20 at 09:48
  • @John_ny https://stackoverflow.com/questions/4413590/javascript-get-array-of-dates-between-2-dates this will help – joy08 Feb 20 '20 at 11:34

5 Answers5

7

You may calculate the difference between dates, than make up desired array of dates casted to date string of necessary format:

const d1 = new Date('02/20/2020'),
      d2 = new Date('03/01/2020'),
      diff = (d2-d1)/864e5,
      dateFormat = {weekday:'long',month:'short',day:'numeric'},
      dates = Array.from(
        {length: diff+1},
        (_,i) => {
          const date = new Date() 
          date.setDate(d1.getDate()+i) 
          const [weekdayStr, dateStr] = date.toLocaleDateString('en-US',dateFormat).split(', ')
          return `${dateStr} ${weekdayStr}`
        }
      )
      
console.log(dates)
.as-console-wrapper {min-height:100%;}

Or, as long as we're having fun here :) following is React implementation:

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

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

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

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 jQuery one:

$(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 d1 = new Date($('#startDate').val()),
            d2 = new Date($('#endDate').val()),
            diff = (d2-d1)/864e5,
            dateFormat = {weekday:'long',month:'short',day:'numeric'},
            dates = Array.from(
              {length: diff+1},
              (_,i) => {
                const date = new Date() 
                date.setDate(d1.getDate()+i) 
                const [weekdayStr, dateStr] = date.toLocaleDateString('en-US',dateFormat).split(', ')
                return `${dateStr} ${weekdayStr}`
              }
            ),
            dateListItems = dates.map(d => `<li>${d}</li>`)
      $('#dateList').html(dateListItems)
    }
  })
        
})
<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>
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
4

you can use momentjs to get the result:


//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>
Tyagi
  • 699
  • 6
  • 6
1

You can start by first creating two date objects, one for the start date and another for the end date. Then, find out how many days are in between these dates. Finally, you can loop through this number and get the current date plus the current index in the loop and print that.

As 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>
Chris
  • 57,622
  • 19
  • 111
  • 137
0

Another method to get the difference between two dates in JavaScript:

const d1 = new Date("06/30/2019"); 
const d2 = new Date("07/30/2019"); 

// To calculate the time difference of two dates 
const timeDiff = d2.getTime() - d1.getTime(); 

// To calculate the no. of days between two dates 
const days = timeDiff / (1000 * 3600 * 24); 

//to list the days
while (days !== 0) {
    let date = new Date(d2)
    date.setDate(date.getDate() - days)
    console.log(date)
    days--
}
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67
  • Your answer does ***not*** deliver expected result (array of date strings adjusted accordingly to OP's format). Besides you may achieve above result subtracting `date2` and `date1` directly (without `.getTime()`) and `1000*3600*24=864e5`, for short – Yevhen Horbunkov Feb 20 '20 at 11:06
0

From the date given, find the difference in days then based on the no of days, make a loop and log each increment day in between 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'}))
}
Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116