loading...

How to use moment.js with React

rossanodan profile image Rossano D'Angelo ・1 min read

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

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>
...

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>
...

Alt Text

Posted on by:

rossanodan profile

Rossano D'Angelo

@rossanodan

Application engineer at The LEGO Group. I like reading manga. All my opinions are belong to me.

Discussion

pic
Editor guide