Search code examples
reactjscalendarreact-date-range

How to get the number of days between start date and end date of a calendar


I'm using "react-date-range" to create a calendar which allows the user to select his check-in and check-out dates. But how do I get the number of days which the user wants to stay for example if I'm selecting 1st as my (start date) and 10th as my (end-date) then the number of days I would be staying in the hotel would be 9. can somebody please help me implement this

My CalendarFunc Component

import React from 'react'
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { DateRangePicker } from 'react-date-range';
import { useState } from 'react';

const CalendarFunc = (props) => {

    const [startDate, setStartDate] = useState(new Date());
    const [endDate, setEndDate] = useState(new Date());



    const handleSelect=(ranges) =>{
        console.log(ranges.selection.startDate);
        console.log(ranges.selection.endDate)
    }


    const selectionRange = {
        startDate: startDate,
        endDate: endDate,
        key: "selection"
    }
    return (<div className='calendarHolder'>
        {props.buttonopenState &&  <DateRangePicker ranges={[selectionRange]} minDate={new Date()} rangeColors={["#FD5B61"]} onChange={handleSelect} /> }


    </div>)
}

export default CalendarFunc

And upon console logging the startDate and endDate this is what I get

Can somebody please help me implement the number of days the user stays in the hotel by subtracting his check-in and check-out date


Solution

  • You could use a package like date-fns to calculate this. You can install it with npm or yarn like this:

    npm install date-fns --save
    # or
    yarn add date-fns
    

    This package has a function called differenceInDays with takes the 2 dates as arguments. You can import it like this:

    import { differenceInDays } from 'date-fns'
    

    and use it like this:

    const date1 = new Date(2020, 5, 1); // the later date
    const date2 = new Date(2020, 2, 1); // the earlier date
    const result = differenceInDays(date1, date2);
    //=> 92
    

    So in your case you could implement it in your handleSelect function this way:

    const [diffInDays, setDiffInDays] = useState(0);
    
    const handleSelect = (ranges) => {
        console.log(ranges.selection.startDate);
        console.log(ranges.selection.endDate);
        const diff = differenceInDays(ranges.selection.endDate, ranges.selection.startDate);
        setDiffInDays(diff);
    }