Tech

How to Handle Date and Time Management in React Using Moment.js



Managing dates and time in React can pose a challenge for those who lack familiarity in 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

Moment.js library is a package for managing 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 from 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

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

The format() method takes a string argument specifying 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
  • YY: Year with two digits
  • MM: Month with two digits
  • M: Month with one or two digits
  • MMMM: 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
  • HH: Hour with two digits
  • H: Hour with one or two digits
  • mm: Minute with two digits
  • m: Minute with one or two digits
  • ss: Second with two digits
  • s: Second with one or two digits

When the App component in the previous code block is rendered, the current date and time are displayed in the specified format on the screen.

The moment() method can take a string date or time argument. When the moment() method has a string date or time argument, it creates a moment object representing 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, lastYear, and hour. These four variables use various methods of the Moment.js library to manipulate date and time.

The tomorrow variable uses the add() method to add one day to the current date. The add() 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, minutes, and 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 set() method, the lastYear variable sets the year to 2022 and the month to February (since January is represented as month 0). The set() method assigns a particular unit of time to a Moment object.

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

Using Moment.js to Parse Date and Time

Another helpful 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() 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() method will parse this string ‘2920130000’ using the “Do-MMMM-YYYY” format string. The toDate() method converts the moment object to a native JavaScript Date object.

The toDate() method takes no arguments and returns a JavaScript Date object representing the same date and time as the moment object.

Displaying Relative Time

With the Moment.js library, you can format and display relative time. To do this, you use the fromNow() and toNow() 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 fromNow() method returns the relative time elapsed since the specified date, while the toNow() method returns the relative time until the current time.

More to Moment.js

Moment.js is a powerful library that provides a simple way to manipulate and format dates and times in JavaScript. You have 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, and so on. However, with the information provided, you are more than prepared to start using Moment.js in your React application.

Related Articles

Leave a Reply

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

Back to top button