5 minute read

In my current work, I often need to manage dates and times in JavaScript/typeScript applications. For this, I used to rely on Moment.js.
Let’s dive into how Moment.js works, how it simplifies date handling, and whether it’s still a good choice for modern development.

Moment.js Docs

Moment.js: Managing Dates and Times in JS

1. What is Moment.js?

Moment.js is a popular JavaScript library used for parsing, validating, manipulating, and formatting dates and times.
Before modern JavaScript provided native solutions, Moment.js was the go-to library for developers who needed advanced date and time management.

2. Why do we need it?

Working with dates and times in JavaScript can be tricky. Here’s why:

  • Parsing and formatting dates manually is error-prone.

  • Different time zones and locales can cause issues.

  • Calculating date differences (like “how many days until the deadline?”) requires careful handling.

Moment.js solves these problems by offering a simple and consistent API.

3. How do you use it?

Step1. Installing Moment.js

To use Moment.js, you first need to install it.

1. Installation

You can install Moment.js using npm or a CDN.

npm install moment

2. Importing Moment.js

If you’re using a module bundler, import Moment.js like this:

import moment from "moment";

Step2. Formatting Dates and Times

Moment.js makes it easy to format dates and times in various ways.

const now = moment();
console.log(now.format("YYYY-MM-DD HH:mm:ss")); // e.g., 2025-01-13 14:30:45

You can use different format strings to display dates in various styles:

  • YYYY: 4-digit year

  • MM: 2-digit month

  • DD: 2-digit day

  • HH: 2-digit hour (24-hour format)

  • mm: 2-digit minute

  • ss: 2-digit second

Step3. Parsing Dates

Parsing a date string and converting it into a Moment.js object is simple.

const date = moment("2025-01-13", "YYYY-MM-DD");
console.log(date.format()); // 2025-01-13T00:00:00+09:00

Step 4: Manipulating Dates

Moment.js allows you to add or subtract time units from a date.

const nextWeek = moment().add(7, "days");
console.log(nextWeek.format("YYYY-MM-DD")); // 2025-01-20

const lastMonth = moment().subtract(1, "month");
console.log(lastMonth.format("YYYY-MM-DD")); // e.g., 2024-12-13

Step 5: Calculating Date Differences

You can easily calculate differences between two dates.

const start = moment("2025-01-01");
const end = moment("2025-01-13");
console.log(end.diff(start, "days")); // 12

Step6. Handling Time Zones

Moment.js also supports time zone conversions (with an additional plugin moment-timezone). This is especially useful when working on applications that need to display the correct time for users in different parts of the world.

To use this feature, you first need to install the moment-timezone package:

npm install moment-timezone

Here’s an example of converting a date and time to a specific time zone:

import moment from "moment-timezone";
const nyTime = moment.tz("2025-01-13 14:00", "America/New_York");
console.log(nyTime.format("YYYY-MM-DD HH:mm:ss")); // e.g., 2025-01-13 14:00:00

Common Use Cases:

Scheduling across time zones: If you’re building an app where users in different time zones schedule events (e.g., meetings or reminders), you can store timestamps in UTC and display them in the user’s local time zone.

const utcTime = moment.utc("2025-01-13 19:00");
const localTime = utcTime.local();
console.log(localTime.format("YYYY-MM-DD HH:mm:ss")); // Converts to local time zone

Displaying the user’s local time:

const userTimeZone = moment.tz.guess(); // Automatically guesses the user's time zone
const localTime = moment.tz("2025-01-13 14:00", userTimeZone);
console.log(localTime.format("YYYY-MM-DD HH:mm:ss"));

Calculating time zone offsets: You can also calculate the time zone offset from UTC for a specific date and time.

const offset = moment.tz("2025-01-13 14:00", "America/New_York").utcOffset();
console.log(offset); // e.g., -300 (offset in minutes)

Using moment-timezone, you can ensure that your application handles time zones correctly and provides a seamless experience for users worldwide.

Moment.js also supports time zone conversions (with an additional plugin moment-timezone).

import moment from "moment-timezone";
const nyTime = moment.tz("2025-01-13 14:00", "America/New_York");
console.log(nyTime.format("YYYY-MM-DD HH:mm:ss")); // e.g., 2025-01-13 14:00:00

Step6-1. Handling Time Zones Use Case in Real-World Scenarios

Moment.js and moment-timezone make it straightforward to handle time zones in applications.
This is particularly useful in scenarios where users in different time zones need to interact with a shared schedule, such as a tutoring app.

Tutor Registers Available Schedule

  • The tutor inputs their available time in their local time zone (e.g., ‘Asia/Seoul’).

  • When storing this information in the database, it should be converted to UTC.

const tutorTime = moment.tz("2025-01-13 14:00", "Asia/Seoul");
const utcTime = tutorTime.utc();
console.log(utcTime.format()); // 2025-01-13T05:00:00Z (converted to UTC)

Displaying Schedule on the Tutor’s Page

  • The stored UTC time is converted back to the tutor’s local time zone for display.
const utcTime = moment.utc("2025-01-13T05:00:00Z");
const tutorLocalTime = utcTime.tz("Asia/Seoul");
console.log(tutorLocalTime.format("YYYY-MM-DD HH:mm:ss")); // 2025-01-13 14:00:00 (in tutor's local time)

Displaying Schedule on the Student’s Page

  • On the student’s page, the tutor’s available schedule is displayed in the student’s local time zone.

  • The student’s time zone can be automatically detected by the browser.

const studentTimeZone = moment.tz.guess(); // Automatically detects the student's time zone
const studentLocalTime = utcTime.tz(studentTimeZone);
console.log(studentLocalTime.format("YYYY-MM-DD HH:mm:ss")); // Converted to student's local time

Summary of the Flow

  • The tutor inputs their schedule, which is stored in UTC.

  • On the tutor’s page, the UTC time is converted back to the tutor’s time zone.

  • On the student’s page, the UTC time is converted to the student’s time zone.

✅ Pros and Cons of Using Moment.js

Pros:

  • Rich feature set: Moment.js provides a comprehensive set of utilities for date and time manipulation.

  • Simple API: Its intuitive API makes it easy to get started.

  • Locale and time zone support: You can easily handle different locales and time zones.

Cons:

  • Bundle size: Moment.js is relatively large compared to modern alternatives.

  • Immutability: Moment.js mutates the original object when manipulating dates, which can lead to bugs.

  • Deprecated: While it still works, Moment.js is no longer actively maintained, and the maintainers recommend using modern alternatives like date-fns or Day.js.

Modern Alternatives to Moment.js

date-fns

  • Lightweight and modular.

  • Provides immutable date manipulation.

Day.js

  • API similar to Moment.js.

  • Much smaller and faster.

Luxon

  • Built by one of Moment.js’s developers.

  • Provides better support for modern JavaScript features.

✅ Bonus

import moment from "moment-timezone";

// 튜터가 PST 시간대로 수업 가능 시간을 입력
const tutorTimePST = moment.tz("2025-01-14 10:00", "America/Los_Angeles");
console.log("Tutor time in PST:", tutorTimePST.format("YYYY-MM-DD HH:mm:ss")); // 2025-01-14 10:00:00

// PST 시간을 UTC로 변환
const utcTime = tutorTimePST.utc();
console.log("Converted UTC time:", utcTime.format("YYYY-MM-DD HH:mm:ss")); // 2025-01-14 18:00:00

// 백엔드로 전송할 UTC 시간
const utcTimeForBackend = utcTime.format(); // 2025-01-14T18:00:00Z

HH:mm vs hh:mm

HH:mm

24시간 형식으로 시간을 표시합니다.
HH는 00부터 23까지의 범위를 가집니다.
오전/오후(AM/PM) 표기가 없습니다.

moment().format("HH:mm"); // 예: 14:30 (오후 2시 30분)

hh:mm

12시간 형식으로 시간을 표시합니다.
hh는 01부터 12까지의 범위를 가집니다.
오전/오후(AM/PM)를 함께 표시하려면 A 또는 a를 추가로 사용해야 합니다.

A: AM/PM (대문자)
a: am/pm (소문자)

moment().format("hh:mm A"); // 예: 02:30 PM (오후 2시 30분)
moment().format("hh:mm a"); // 예: 02:30 pm (오후 2시 30분)

Conclusion

In this post, we explored how to use Moment.js for handling dates and times in JavaScript. While it’s still a useful tool, modern alternatives offer better performance and a smaller footprint. If you’re working on a new project, consider using date-fns or Day.js instead.