TUTORIAL
How to Use Moment.js in React
by Jon Welling
Project Overview
EXPERIENCE LEVEL: Intermediate
TIME TO COMPLETE: 45 minutes
ESTIMATED COST: Free (assuming you already have Node/React environment set up)
Skills Needed
Familiarity with React basics
Comfort with JavaScript functions and arrays
Basic understanding of npm package management
Tools and Materials Needed
A working React environment (e.g., create-react-app)
Node.js and npm installed
Code editor (VS Code recommended)
Browser console for debugging
Before You Begin
Before working with Moment.js in React:
Make sure you have a React app scaffolded (or create one with npx create-react-app my-app).
Install Moment.js by running npm install moment.
Brush up on JavaScript array methods like .push() and looping constructs — you’ll need them.
How to Use Moment.js in React to Build a Data Picker
Have you ever tried to build a date picker in React? Using JavaScript’s native Date object can quickly turn into a mess of manual calculations. That’s where Moment.js comes in—it's a JavaScript library that makes it a lot easier to parse, validate, and manipulate date objects in JavaScript.
While Moment.js makes working with dates much easier than vanilla JavaScript, keep in mind that the library is in maintenance mode. If you’re starting a brand-new project, you may also want to look at lighter alternatives like Day.js or date-fns. However, if you’re working with an existing React app that already uses Moment.js, it’s still an excellent tool to know.
Let’s walk through how to use Moment.js to work with dates in React, step by step.
Step 1: Import Moment.js
To get started, you'll first need to import the Moment library into your React project:
import moment from "moment";Step 2: Format Dates
Once that is done, you'll need to set your preferred date format. Here we’ll use American standards:
moment().format("MM/DD/YYYY");Step 3: Parse Dates
You can also parse a specific date string:
moment("01/01/1999", "MM/DD/YYYY");Setting the date isn't super useful unless you also store it as a variable so you can reuse it later. Here's how to do that:
const aLongTimeAgo = moment("01/01/1999", "MM/DD/YYYY");Step 4: Get the Month and Days in a Month
Once you have a Moment object, you can retrieve the month and total number of days:
// Current month
aLongTimeAgo.month();
// Total days in the month
aLongTimeAgo.daysInMonth();
You can also add or subtract days:
// Five days later
aLongTimeAgo.add(5, "days");
// Five days earlier
aLongTimeAgo.subtract(5, "days");Step 5: Find the First Day of the Month
Want the very first day of the month?
aLongTimeAgo.startOf("month");Note: Moment objects are mutable. If you change one, it updates the original. Use .clone() if you need a copy:
const newMoment = aLongTimeAgo.clone();Step 6: Count Days in a Month
Let’s put everything together to figure out how many days are in the current month.
import moment from "moment";
const getDaysInMonth = (monthMoment) => {
  const monthCopy = monthMoment.clone();
  monthCopy.startOf("month");
  let days = [];
  while (monthCopy.month() === monthMoment.month()) {
    days.push(monthCopy.clone());
    monthCopy.add(1, "days");
  }
  return days;
};
const days = getDaysInMonth(moment());
console.log("days:", days);This function:
Clones the current month
Sets the clone to the first day of the month
Loops through all days in the month, adding them to an array
Returns the array
Each day object in the array contains information, such as the day of the week, which makes it easy to filter and count. Want to take this experiment a step forward? Loop through the array and count the number of Tuesdays this month.
Common Pitfalls to Watch Out For
Moment.js takes away a lot of the pain of working with dates, but there are still a few common gotchas to keep in mind:
Time Zones: By default, Moment works off the system’s local time zone. If you’re building something where users are in different locations (e.g., a booking system or event calendar), you’ll want to use the companion library moment-timezone. Otherwise, you might end up showing the wrong day or time for certain users.
Mutability: Moment objects are mutable, meaning when you call methods like .add() or .subtract(), you’re changing the original object. This can cause sneaky bugs if you’re reusing that object elsewhere in your code. Always use .clone() first if you want to preserve the original.
International Dates: Moment supports multiple locales, but you have to explicitly load and set them. If you’re working on an app for users outside the U.S., forgetting to do this could mean your dates display in the wrong format (for example, MM/DD/YYYY vs. DD/MM/YYYY).
Conclusion
Moment.js saves you from a lot of painful Date math when building apps in React. With just a few lines of code, you can parse dates, count days in a month, and even determine how many Tuesdays occur.
Want to learn more? Check out Shaun Wassell’s React Datepicker from Scratch course at CBT Nuggets or browse all our tutorials.