Get date Dange in React without a framework.

Get date Dange in React without a framework.

Table of contents

No heading

No headings in the article.

At the end of this article, you will write code to get the range between dates in JavaScript. JavaScript is a flexible and complex language, which can be quite annoying at times. πŸ˜‚ I spent hours debugging, trying to figure out why my code wasn't calculating. I didn't know that JavaScript sees HTML dates as strings. In this article, you will learn how to get the date in both JavaScript and TypeScript.

let’s get started. happy πŸ˜†

First, we must begin the project. No further preparation is necessary.

Run the command npx create-react-app range-date or yarn create react-app range-date to create a React app with a range date feature.

After initializing it, open the folder in your favorite code editor. It will look like this if you're using VSCode, like me.

image

Go to your app.js file and remove the HTML code. Create a h1 tag inside a div and make it say "Date Range Checker".

We'll use the React hook useState to track our state. Create two variables: startDate and endDate, and two functions: setStartDate and setEndDate. When setting a new date, the code should look like this:

// JAVASCRIPT CODE
const [startDate, setStartDate] = useState(new Date())
const [endDate, SetEndDate] = useState(new Date())

// TYPESCRIPT CODE
const [startDate, setStartDate] = useState<Date>(new Date())
const [endDate, SetEndDate] = useState<Date>(new Date())

Create a function called calculateDays() which takes two arguments, start and end, to calculate the number of days between them.

// JAVASCRIPT CODE
function calculateDays(start, end){
    //calculating the time difference
    const differentTime = Math.abs(end.getTime() - start.getTime());

    //calculating the days difference between the start and end dates
    const differentDays = Math.ceil(differentTime / (1000 * 60 * 60 * 24));

        // use a return statement if don't want console it - return differentDays
    // console.log(differentDays)
        return date
  }


// TypeScript code
function calculateDays(start:Date, end:Date){
    //calculating the time difference
    const differentTime = Math.abs(end.getTime() - start.getTime());

    //calculating the days difference between the start and end dates
    const differentDays = Math.ceil(differentTime / (1000 * 60 * 60 * 24));

        // use a return statement if don't want console it - return differentDays
    console.log(differentDays)
  }

The function created above calculates a start and end. It will subtract the difference between them. Create a form with two inputs and a button.

code

<div className="App">
      <h1> Date range app</h1>
      <form>
        <input type="date"  onChange={(event) => setStartDate(new Date(event.target.value))} />
        <input type="date"  onChange={(event) => setEndDate(new Date(event.target.value))} />
        <button type="submit" onClick={calculateDays(startDate, endDate)}>calculate date</button>
      </form>
    </div>

In the code, the onChange event will capture the user's input and store it in the useState variable we created earlier. The button has an onClick event that calls the function we created, providing the number of days between the start and end.

However, there is a problem: if we call the function, we will get an error.

output errorUncaught TypeError: start.getTime is not a function at calculateDays

While we encounter this error, it is because JavaScript stores the HTML date as a string. To resolve this issue, we are going to use a date method in JavaScript called new Date() in our onChange event listener. This date method will convert our date strings into Date objects, that are more easily readable and manipulable by JavaScript. Furthermore, this Date object will help us to determine the exact date and time that a user is selecting, and will allow us to accurately manipulate the data with more precise methods..

code.

<div className="App">
      <h1> Date range app</h1>
      <form>
        <input type="date"  onChange={(event) => setStartDate(new Date(event.target.value))} />
        <input type="date" onChange={(event) => SetEndDate(new Date(event.target.value))} />
        <button type="submit" onClick={calculateDays(startDate, endDate)}>calculate date</button>
      </form>
    </div>

Now that we have the code in place, we can test it out. Open your browser, and enter the URL localhost:3000. You should see the date range app, with two date pickers and a button. Input two dates, and click the button to see the number of days between them in your console.

The function is now running optimally. Thank you for taking the time to read this article. Hope you have gained some useful knowledge from it. If so, I invite you to follow us for more informative articles like this. We will always strive to provide the best content and continuously improve our offerings to ensure your satisfaction. Thank you for your support!

Β