Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the full dates between two dates using javascript / react?

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?

like image 896
John_ny Avatar asked Dec 14 '22 09:12

John_ny


1 Answers

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>
like image 175
Yevgen Gorbunkov Avatar answered Dec 17 '22 23:12

Yevgen Gorbunkov