How to get the current Year in React

avatar

Borislav Hadzhiev

Last updated: May 1, 2022

banner

Photo from Unsplash

Get the current Year in React #

Use the Date() constructor to get the current year in React, e.g. new Date().getFullYear(). The getFullYear() method will return a number that corresponds to the current year.

App.js
const App = () => { console.log(new Date().getFullYear()); return ( <div> <div>{new Date().getFullYear()}</div> <br /> <div>Copyright © {new Date().getFullYear()} James Doe</div> </div> ); }; export default App;

react get current year

We used the Date() constructor to get a Date object, on which we can call various methods.

We then called the Date.getFullYear method, which returns a number representing the year that corresponds to the current date.

Notice that we had to wrap the call to the getFullYear() method in curly braces in our JSX code.

App.js
<div>{new Date().getFullYear()}</div>
The curly braces mark the beginning of an expression that has to be evaluated.

The JavaScript code between the curly braces will get evaluated with the current year.

Other commonly used methods on the Date object are:

  • Date.getMonth - returns an integer between 0 (January) and 11 (December) and represents the month for a given date. Yes, unfortunately the getMonth method is off by 1.
  • Date.getDate - returns the day of the month for a specific date
App.js
const App = () => { const year = new Date().getFullYear(); const month = new Date().getMonth() + 1; const day = new Date().getDate(); return ( <div> <div>{new Date().getFullYear()}</div> <div>{new Date().getMonth() + 1}</div> <div>{new Date().getDate()}</div> <br /> <div>Copyright © {new Date().getFullYear()} James Doe</div> </div> ); }; export default App;

These methods allow you get the year / month / day for any date object, it doesn't have to be the current year.

App.js
const App = () => { const date = '2023-07-21'; const year = new Date(date).getFullYear(); const month = new Date(date).getMonth() + 1; const day = new Date(date).getDate(); return ( <div> <div>{new Date(date).getFullYear()}</div> <div>{new Date(date).getMonth() + 1}</div> <div>{new Date(date).getDate()}</div> <br /> <div>Copyright © {new Date(date).getFullYear()} James Doe</div> </div> ); }; export default App;
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.