How to format Date in React JS

Share the post

Hello All, In this React JS tutorial We would learn about How to format Date in React JS. In the last React JS tutorial, We had discussed What is React Fragment in React JS.

You might have heard about moment JS, but after reading this article you will get a complete idea about How to format Date in React JS using moment JS.

In this React JS tutorial, We will discuss How to format Date in React JS using moment JS with the help of an example.

So, let’s Start…

How to format Date in React JS using Moment | Example of Date format in React JS using moment

Create a new React JS project using the below command

npx create-react-app reactapp

To demonstrate How to format Date in React JS we first need to install moment js npm dependency by using the following command

npm i --save moment react-moment

After, Installing the dependency we need to import the moment module by using the following command

import moment from 'moment';

Now, After importing the module we can start working with dates. We will perform some Date formating which we are widely using while programming.

  • To display the current date in a particular format
{moment().format('YYYY-MM-DD')}
  • To convert one Date format to another format
{moment('30JANUARY2020').format('YYYY-MM-DD')}
  • To get a full date with timestamp in a particular format
{moment().format("dddd, MMMM Do YYYY, h:mm:ss a")}
  • To get days in the month
{moment().daysInMonth()}
  • To get the difference between the 2 days
{moment([2020, 0, 20]).diff([2019, 0, 20], 'days')}

Complete Source Code

import './App.css';
import React from 'react';
import moment from 'moment';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h2>
          How to format date using moment in react js
        </h2>
        <div>
          <div>To display current date in particular format</div>
          <div>{moment().format('YYYY-MM-DD')}</div>
        </div>

        <div>
          <div>To convert one date format to other format</div>
          <div>{moment('30JANUARY2020').format('YYYY-MM-DD')}</div>
        </div>

        <div>
          <div>To get full date with timestamp in particular format</div>
          <div>{moment().format("dddd, MMMM Do YYYY, h:mm:ss a")}</div>
        </div>

        <div>
          <div>To get days in month</div>
          <div>{moment().daysInMonth()}</div>
        </div>

        <div>
          <div>To get difference between 2 days</div>
          <div>{moment([2020, 0, 20]).diff([2019, 0, 20], 'days')}</div>
        </div>

      </header>

    </div>
  );
}

export default App;

Now, Run the React JS Project using the following command

npm run start

Output

How to format Date in React JS
How to format Date in React JS

1 thought on “How to format Date in React JS”

Leave a Comment