How to handle date and time management in React using Moment.js

Managing dates and times in React can be challenging for those unfamiliar with the area. Fortunately, there are several libraries that can help you with date and time management in React. One of these libraries is Moment.js.


Moment.js is a lightweight library with a simple way to manipulate and format dates and times in JavaScript.


Installing the Moment.js library

The Moment.js library is a package for handling date and time operations in JavaScript. Installing the Moment.js library is the first step in using Moment.js in your React application. You can do this by running the following command in your terminal:

 npm install moment

Once the installation is complete, you can use Moment.js in your React component.

Using Moment.js to display date and time

You can use Moment.js to display dates and times in a specific format within your React app. To use the library, import moment of the installed package.

 import React from 'react';
import moment from 'moment';

function App() {

  const date = moment().format("MMMM DD YYYY");
  const time = moment().format("HH mm ss");

  return (
    <div>
      <p> Today's date is { date } </p>
      <p> The time is { time } </p>
    </div>
  )
}

export default App

He moment() The method creates a new moment object that represents a specific point in time. He Format() The method formats a moment object into a string representation.

He Format() The method takes a string argument that specifies the desired format for the moment object. The string argument can include a combination of letters and special characters, each with a specific meaning.

Some of these special characters are:

  • YYYY: Year with four digits
  • AA: Year with two digits
  • millimeter: Month with two digits
  • METER: Month with one or two digits
  • MMMMM: month in words
  • DD: Day of the month with two digits
  • D.: Day of the month with one or two digits
  • Do: Day of the month with the ordinal
  • H.H: Hour with two digits
  • h: Hour with one or two digits
  • millimeter: Minute with two digits
  • meter: Minute with one or two digits
  • H.H: Second with two digits
  • yes: Second with one or two digits

when the application component in the code block above, the current date and time are displayed in the format specified on the screen.

He moment() The method can take a string date or time argument. when the moment() has a string date or time argument, it creates a moment object that represents that date or time. The string can be in various formats, such as ISO 8601, RFC 2822, or Unix timestamp.

For example:

 const date = moment('1998-06-23').format("MMMM DD YYYY");

Using Moment.js to manipulate date and time

The Moment.js library also provides several methods for manipulating dates and times. These methods allow you to add or subtract time intervals, set specific values ​​for date and time components, and perform other applicable operations.

For example:

 import React from 'react';
import moment from 'moment';

function App() {

  const tomorrow = moment().add(1, 'day').format("Do MMMM,YYYY");
  const time = moment().subtract(1, 'hour').format("HH:mm:ss");
  const lastYear = moment().set('year', 2022).set('month', 1).format("Do MMMM,YYYY");
  const hour = moment().get('hour');

  return (
    <div className="App">
      <p>Tomorrow's date is { tomorrow }</p>
      <p>This was the time: { time }, an hour ago</p>
      <p>{ lastYear }</p>
      <p>{ hour }</p>
    </div>
  )
}

export default App

In this example, you declare the following JavaScript variables: tomorrow, time, last yearand hour. These four variables use various methods from the Moment.js library to manipulate the date and time.

He tomorrow variable uses the add() method to add a day to the current date. He add() The method adds time to a given Moment object. The function takes two arguments: a duration value and a string representing the unit of time to add. The unit could be years, months, weeks, days, hours, minutesand seconds.

You can also subtract time using the subtract() method. In this case, the time variable uses the subtract() method to subtract one hour from the current time.

Using the place() method, the last year variable sets the year to 2022 and the month to February (since January is represented as month 0). He place() The method assigns a particular time unit to a Moment object.

With the get() method, you can retrieve a specific time. He get() The method takes a single argument, a unit of time.

Using Moment.js to parse date and time

Another useful feature of Moment.js is its ability to parse dates and times from strings. This can be useful when working with data from external sources.

To parse a date or time from a string, you need to use the moment() method. In this case, the moment() The method takes two arguments, the date string and a format string.

Here is an example of how you can use the moment() method to parse dates and times:

 import React from 'react';
import moment from 'moment';

function App() {

  const date = moment('2920130000', 'Do-MMMM-YYYY').toDate();
  console.log( date );

  return (
    <div></div>
  )
}

export default App

In the code block above, moment() The method will parse this string ‘2920130000’ using the format string “Do-MMMM-YYYY”. He till the date() The method converts the moment object to a native JavaScript Date object.

He till the date() The method takes no arguments and returns a JavaScript date object that represents the same date and time as the moment object.

Relative time display

With the Moment.js library, you can format and display relative time. To do this, use the from now() and for now() methods. These methods display the time between a given date and the current time.

For example:

 import React from 'react';
import moment from 'moment';

function App() {

  const yesterday = moment().subtract(7, 'day');
  const time1 = yesterday.fromNow();
  const time2 = yesterday.toNow();

  return (
    <div>
     <p>{ time1 }</p>
     <p>{ time2 }</p>
    </div>
  )
}

export default App

In this example, the from now() returns the relative time elapsed since the specified date, while the for now() method returns the relative time up to the current time.

More on Moment.js

Moment.js is a powerful library that provides an easy way to manipulate and format dates and times in JavaScript. You’ve learned how to manipulate, display, and parse dates and times in React using Moment.js.

Moment.js offers several other methods, such as local, startOf, endOf, etc. However, with the information provided, you’re more than ready to start using Moment.js in your React app.