DEV Community

Rossano D'Angelo
Rossano D'Angelo

Posted on

React Moment How to use moment.js with React

Introduction

After some refactoring and some adjustments, my football almanac application looks like this

Alt Text

Alt Text

There is a last thing to work on: the date and time of each match.

Installing moment.js

I install moment.js

npm install --save moment react-moment
Enter fullscreen mode Exit fullscreen mode

and I import it in the Match.tsx component

import Moment from 'react-moment';
...
<div className={classes.cardHeader}>
  <Typography variant="overline" display="block" gutterBottom>
    <Moment>{utcDate}</Moment>
  </Typography>
</div>
...
Enter fullscreen mode Exit fullscreen mode

In this way, I obtain the date and time formatted

Alt Text

Advanced formatting

moment.js allows different date formats. If you want to learn more about it, visit the official documentation.

I prefer a more readable format. Something like 1st January 2020 - 19.00 should work.

...
<Moment format="Do MMMM YYYY - HH:mm">{utcDate}</Moment>
...
Enter fullscreen mode Exit fullscreen mode

Alt Text

Top comments (0)