How to Install & Use Moment.js in React

Published on September 11, 2020 1 min read

In this guide, I’m going to show how to setup and use moment.js in React. Let’s get started:

Table of Contents

  1. Installation
  2. Examples

Installation

We can use only moment package but I I’ll suggest you to use react-moment too. It comes with handy JSX tags which reduce a lot of work.

npm install --save moment react-moment

Optional: You can also install moment-timezone package. It is required to use the timezone related functions.

npm install --save moment-timezone

Examples

Now let’s see some examples.

Get current datetime:

App.js
import React from 'react';

import moment from 'moment'
import Moment from 'react-moment';

function App() {
  const currentDateTime = moment()

  return(
    <Moment>{currentDateTime}</Moment>
  )
}

export default App;

Format datetime:

import React from 'react';

import moment from 'moment'
import Moment from 'react-moment';

function App() {
  const currentDateTime = moment()

  return(
    <Moment format='MMMM Do YYYY, h:mm:ss a'>{currentDateTime}</Moment>
  )
}

export default App;

Add and Subtract:

import React from 'react';

import moment from 'moment'
import Moment from 'react-moment';

function App() {
  const currentDateTime = moment()

  return(
    <div>
      <Moment add={{ hours: 12 }}>{currentDateTime}</Moment> <br/>
      <Moment add={{ days: 1, hours: 12 }}>{currentDateTime}</Moment> <br/>
      <Moment subtract={{ hours: 12 }}>{currentDateTime}</Moment> <br/>
      <Moment subtract={{ days: 1, hours: 12 }}>{currentDateTime}</Moment>
    </div>
  )
}

export default App;

Use of Timezone:

import React from 'react';

import moment from 'moment'
import Moment from 'react-moment';
import 'moment-timezone';

function App() {
  const currentDateTime = moment()

  return(
    <div>
      Dhaka: <Moment unix tz="Asia/Dhaka">
          {currentDateTime}
      </Moment><br/>
      Los Angeles: <Moment unix tz="America/Los_Angeles">
          {currentDateTime}
      </Moment>
    </div>
  )
}

export default App;

Have a look at moment.jsreact-moment & moment-timezone pages to learn more.

That’s it. Thanks for reading. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *