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?

2
  • 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. Commented Feb 20, 2020 at 9:48
  • @John_ny stackoverflow.com/questions/4413590/… this will help Commented Feb 20, 2020 at 11:34

5 Answers 5

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>

Sign up to request clarification or add additional context in comments.

3 Comments

i would to get the days for repestive dates as well.
Having fun? :-D
@YevgenGorbunkov oh, well I think I submitted my answer like 1 minute after yours and so, yes, since OP asked about js or react, I thought I'd do something slightly different. :)
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>

Comments

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>

Comments

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'}))
}

4 Comments

There's no need for Math.ceil() (which can be done as const diffDays = 0|diffTime/864e5, as long as your attempt was to post shorter way), since resulting timestamps would be divisible by (1000*60*60*24, by default)
@YevgenGorbunkov, Thanks for pointing out, have updated answer..
You're most welcome, there's another move you can make - your date string format is somewhat different from requested (refer to OP for details).
And, by the way, you can make (i*24*60*60*1000) shorter in the same way: i*864e5
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--
}

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.