How to use Date() constructor in React




In this post, we are going to see how can we get the current date inside a react component.

Date() constructor

To get the current date inside a react component we use the Date() constructor
It has various methods like
getFullYear() => returns the year as a four digit number

getMonth() => returns month as a number

getDate() => returns the day as a number

getHours() => returnsthe hour

getMinutes() => returns the minute

getSeconds() => returns the second

getMilliseconds() => returns the millisecond

getTime() => returns the time

getDay() => returns the weekday as a number

Date.now() => returns the time.

example

import React from "react";

export default function App() {
  const date = new Date();
  const year = date.getFullYear();

  return (
    <div className="App">
      <h1>The Current year is {year}</h1>
    </div>
  );
}

the output will be like

The current year is 2020