Moment.js Cheatsheet



Moment.js is a powerful JavaScript library that is used for parsing, validating, manipulating, and formatting dates and times.

This Moment.js cheatsheet provides the basic and advanced concepts of Moment.js with the help of examples and references to Moment.js functions and methods.

Table of Contents

Introduction

Moment.js is a popular library of JavaScript which is used to manipulate dates and times. It allows us to parse, format, manipulate, and display dates in many different ways. For instance, you can transform a date string to a particular format, perform time comparisons, process time zones, etc. It can be very helpful when doing various projects with high accuracy over date and time operations such as calendars, scheduling, data reporting, etc. Newer libraries, such as Luxon, are now recommended for new applications, but Moment.js is still well-known for its speed and stability.

Basic Examples

Learn how to create Moment.js objects for current or specific dates, retrieve Unix timestamps, convert timestamps to readable formats, and clone objects efficiently.

Create a Moment Object for the Current Date and Time

Initialize a Moment.js object to represent the current date and time, providing a snapshot of the system clock.

const currentTime
= moment();<br>console.log(currentTime.format()); // Displays the current date and time

Create a Moment Object for a Date

Parse a specific date by providing the date string and format, creating a Moment.js object for that date.

const givenDate = moment("2024-12-31", "YYYY-MM-DD"); 
console.log(givenDate.format("YYYY-MM-DD")); // Displays '2024-12-31'

Retrieve the Current Unix Timestamp

Get the Unix timestamp, which counts seconds since January 1, 1970, using Moment.js for precise time calculations.

const unixTime = moment().unix();
console.log(unixTime); // Displays the Unix timestamp (seconds since 1970)

Convert a Unix Timestamp to a Human-Readable Date

Transform a Unix timestamp into a formatted, human-readable date using Moment.js's formatting capabilities.

const readableDate = moment.unix(1704067200);
console.log(readableDate.format("YYYY-MM-DD")); // Displays the formatted date

Duplicate a Moment Object

Clone an existing Moment.js object to create a new one with identical date and time values.

const baseMoment = moment();
const duplicateMoment = baseMoment.clone();
console.log(duplicateMoment.format()); // Matches the baseMoment's date and time

Loading / Installing

Include Moment.js in your project using HTML <code>&lt;script&gt;</code> tags, a CDN link, or npm for streamlined development and compatibility.

HTML

Include Moment.js in your project using a <script> tag to link the library from a CDN.

<script type="text/javascript" 
   src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js">
</script>

CDN

Use the provided CDN link to directly access Moment.js without downloading it locally.

https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js

NPM

Install Moment.js via npm for seamless integration into Node.js or modern JavaScript workflows.

npm install
moment

Parsing

Initialize Moment.js objects from strings (e.g., "YYYY-MM-DD"), Unix timestamps, object literals, or arrays, ensuring flexibility in input formats.

Now

Create a Moment.js object for the current date and time instantly using moment().

moment()

String

Parse dates from strings with custom formats like moment("1977-09-05", "YYYY-MM-DD").

moment("1977-09-05", "YYYY-MM-DD")

Unix

Convert Unix timestamps into Moment.js objects using moment.unix().

moment.unix(0123456789)

Object

Construct dates from detailed object properties like { year: 1977, month: 8, day: 5 }.

moment({ year: 1977, month: 8, day: 5, hour: 12, minute: 30, second: 45 })

Array

Create dates from arrays with specific components like [1977, 8, 5, 12, 30, 45].

moment([1977, 8,
5, 12, 30, 45, 0])

Get / Set

Retrieve or modify individual date components like year, month, or day using intuitive methods.

Property Get Set
Second .second() .second(0-59)
Minute .minute() .minute(0-59)
Hour .hour() .hour(0-23)
Day of Week .day() .day(0-6)
Day of Month .date() .date(1-31)
Day of Year .dayOfYear() .dayOfYear(0-366)
Week of Year .week() .week(1-53)
Month .month() .month(0-11) or .month('Jan')
Year .year() .year(YYYY)

Properties

Use methods like .year(), .month(),.date(), and .hour() to access or update specific time components.

Formatting

Format dates and times into readable strings with tokens like YYYY-MM-DD or customize outputs for advanced needs.

Format Output Example
Datetime .format("YYYY-MM-DD HH:mm:ssZ")
Year YY (15), YYYY (2015)
Month Numeric M (1+), MM (01+)
Month Alpha MMM (Jan), MMMM (January)
Day of Month D (1+), Do (1st), DD (01)
Day of Year DDD (1), DDDo (1st), DDDD (001)
Day of Week d (0), dd (Su), ddd (Sun), dddd (Sunday)
Hour 24h H (0+), HH (00+)
Hour 12h h (1+), hh (01+)
Minute m (0+), mm (00+)
Second s (0+), ss (00+)
Second Fractional S (0-9), SS (00-99)
Zone Z (-00:00), ZZ (-0000)
Unix Timestamp X (0123456789)
Unix Millisecond x (0123456789012)
Key Formats to Master Y, M, D, H, m, s, Z, X

Localization

Adapt date formats to different languages or regions and retrieve the current locale for tailored outputs.

Set Locale

Use moment.locale('fr') to switch to a specific locale for formatting.

moment.locale('fr');

Get Current Locale

console.log(moment.locale());

Localized Date Formatting

Generate localized date strings like 'dimanche 31 dcembre 2024' with moment().format('LLLL').

moment().format('LLLL'); // e.g., 'dimanche 31 dcembre 2024 12:00'

Relative Time

Generate human-readable relative times like "in 3 days" or "2 years ago" for dynamic outputs.

From Now

Use .fromNow() to calculate time differences relative to the current moment.

moment("2024-12-
31").fromNow();

To Now

Apply .toNow() for reverse-relative time comparisons.

moment("2024-12-
31").toNow();

From Specific Date

Compare specific dates with .from() for detailed time differences.

moment("2024-12-
31").from("2024-01-01");

Zones

Manage UTC and time zones, including offset adjustments and conversions.

Action Command
Convert to UTC .utc()
Get UTC Offset .utcOffset()
Set UTC Offset .utcOffset(Number)

Manipulation

Modify dates by adding, subtracting, or constraining values for versatile date handling.

Action Command Example
Get Start of Period .startOf('week')
Get End of Period .endOf('week')
Check If Before .isBefore('1977-09-05', 'year')
Check If After .isAfter('1977-09-05', 'year')
Check If Same .isSame('1977-09-05', 'year')
Check If Between .isBetween('1977-09-01', '1977-09-10', 'day')
Add Time to Date .add(4, 'days')
Subtract Time from Date .subtract(4, 'days')
Constrain Max .max(moment().add(1, 'day'))
Constrain Min .min(moment().subtract(1, 'day'))
Check Validity .isValid()

Duration and Time Differences

Work with durations and differences between dates in units like days, hours, or minutes.

Create Duration

Define durations like moment.duration() for precise time spans.

const duration =
moment.duration(2, 'hours');

Add Duration

Add durations to dates using .add(duration) for calculated future times.

const newDate =
moment().add(duration);

Difference Between Dates

Calculate differences between dates in various units with .diff().

const diff =
moment("2024-12-31").diff(moment("2024-01-01"), 'days');<br>console.log(diff); //

Output

365

Time Comparison

Compare dates with methods like .isBefore(), .isAfter(), and .isSame() for logic-based operations.

Is Before

Check if one date is earlier than another, comparing specific time units if needed (e.g., day, month, or year).

moment("2024-12-
31").isBefore("2025-01-01");

Is After

Determine if one date occurs later than another, allowing for comparisons at various levels of granularity.

moment("2024-12-
31").isAfter("2024-01-01");

Is Same

Verify whether two dates are exactly the same, down to the specified time unit like day, hour, or second.

moment("2024-12-
31").isSame("2024-12-31");

Validation

Ensure dates are valid with .isValid() to handle errors and prevent invalid inputs.

Check If Date Is Valid

const isValid = moment("Invalid Date").isValid();
console.log(isValid); // Output: false

Output

false

Chaining

Combine operations such as adding days, subtracting hours, and formatting for efficient workflows.

Chain Multiple Operations

const chainedDate = moment().add(7, 'days').subtract(2, 'days').startOf('day');
console.log(chainedDate.format("YYYY-MM-DD"));

Example Code

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Moment.js with TutorialsPoint</title>
   <!-- Load Moment.js -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
   <style>
      body {
         font-family: Arial, sans-serif;
         background: linear-gradient(120deg, #51ff00, #007d04);
         color: #fff;
         text-align: center;
         padding: 20px;
      }
      h1 {
         font-size: 2.5em;
         margin-bottom: 10px;
      }
      p {
         font-size: 1.2em;
         margin: 10px 0;
      }
      .container {
         margin: 20px auto;
         padding: 20px;
         background: rgba(0, 0, 0, 0.3);
         border-radius: 10px;
         max-width: 600px;
      }
      .output {
         background: #222;
         padding: 10px;
         border-radius: 5px;
         margin: 10px 0;
      }
      .btn {
         display: inline-block;
         padding: 10px 20px;
         color: #fff;
         background: #4cd800;
         border: none;
         border-radius: 5px;
         cursor: pointer;
         margin: 10px 5px;
         font-size: 1em;
         text-transform: uppercase;
      }
      .btn:hover {
         background: #4dacff;
      }
   </style>
</head>
<body>
    <h1>Welcome to TutorialsPoint</h1>
    <p>Explore the magic of Moment.js through interactive examples!</p>

    <div class="container">
       <h2>Current Date and Time</h2>
       <p id="current-date" class="output">Loading...</p>

       <h2>Parsed and Formatted Date</h2>
       <p id="parsed-date" class="output">Loading...</p>

      <h2>Relative Time</h2>
      <p id="relative-time" class="output">Loading...</p>

      <h2>Time Manipulation</h2>
      <button class="btn" onclick="showNextWeek()">Next Week</button>
      <button class="btn" onclick="showLastMonth()">Last Month</button>
      <p id="manipulated-time" class="output">Click a button to manipulate time</p>

      <h2>Duration and Difference</h2>
      <p id="duration-diff" class="output">Loading...</p>

      <h2>Validation</h2>
      <p id="validation" class="output">Loading...</p>
   </div>

   <script>
      // Initialization and Current Time
      const now = moment();
      document.getElementById("current-date").textContent = now.format("dddd, MMMM Do YYYY, h:mm:ss a");

      // Parsing and Formatting
      const date = moment("2024-12-31", "YYYY-MM-DD");
      document.getElementById("parsed-date").textContent = date.format("Do MMMM, YYYY");

      // Relative Time
      document.getElementById("relative-time").textContent = moment("2024-12-25").fromNow();

      // Time Manipulation Functions
      function showNextWeek() {
         const nextWeek = now.clone().add(7, "days");
         document.getElementById("manipulated-time").textContent = "Next Week: " + nextWeek.format("YYYY-MM-DD");
      }

      function showLastMonth() {
         const lastMonth = now.clone().subtract(1, "months");
         document.getElementById("manipulated-time").textContent = "Last Month: " + lastMonth.format("YYYY-MM-DD");
      }

      // Duration and Time Differences
      const duration = moment.duration(5, "days").humanize();
      const diff = moment("2025-01-01").diff(moment("2024-12-25"), "days");
      document.getElementById("duration-diff").textContent = `5 Days Duration: ${duration}, Days Until New Year: ${diff}`;

      // Validation
      const invalidDate = moment("2024-02-30", "YYYY-MM-DD");
      document.getElementById("validation").textContent = `Date Validation: ${invalidDate.isValid() ? "Valid" : "Invalid"}`;
   </script>
</body>
</html>
Advertisements