Getting the First and Last Day of the Current Month with Moment.js

Nov 21, 2025 · Programming · 10 views · 7.8

Keywords: Moment.js | Date Handling | JavaScript

Abstract: This article explores how to use the Moment.js library to retrieve the first and last day of the current month, formatted to a specific pattern. It begins with an introduction to Moment.js basics, then delves into the workings of the startOf and endOf methods, illustrated with code examples. The discussion also covers Moment.js's status in modern JavaScript development, its mutability characteristics, size concerns, and recommended alternatives like Luxon and Day.js. Complete code snippets and best practices are provided to aid developers in efficient date-time manipulation.

Introduction

Handling dates and times is a common yet complex task in JavaScript development. Moment.js is a widely-used library that offers a rich API to simplify date-time operations. This article focuses on using Moment.js to get the first and last day of the current month, formatted as "2016-09-01 00:00".

Overview of Moment.js

Moment.js is a lightweight JavaScript date library for parsing, validating, manipulating, and displaying dates and times. It supports various input formats and provides method chaining and internationalization. Although Moment.js is still prevalent in legacy projects, it has been marked as a legacy project by its maintainers, who recommend using modern alternatives like Luxon or Day.js for new projects. However, for existing systems or specific needs, Moment.js remains a powerful tool.

Core Methods for Retrieving Month Start and End

In Moment.js, obtaining the first and last day of the current month is straightforward with the startOf('month') and endOf('month') methods. Available since version 1.7, these methods return a moment object adjusted to the start or end of the specified unit.

Here is a complete code example demonstrating how to get the first and last day of the current month and format it as "YYYY-MM-DD hh:mm":

const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
const endOfMonth = moment().endOf('month').format('YYYY-MM-DD hh:mm');

In this example, moment() creates a moment object representing the current date and time. startOf('month') adjusts this object to the first day of the current month, setting the time to 00:00:00. endOf('month') adjusts it to the last day of the month, with the time set to 23:59:59.999. The format('YYYY-MM-DD hh:mm') method converts the moment object to a string, where "YYYY" is the four-digit year, "MM" is the two-digit month, "DD" is the two-digit day, "hh" is the hour in 12-hour format, and "mm" is the minutes.

Method Mechanism Explained

The startOf and endOf methods are key functions in Moment.js for setting date-times to the beginning or end of a specific unit. They work by internally adjusting the components of the date object. For instance, startOf('month') sets the date to the first day of the month and resets the hours, minutes, seconds, and milliseconds to zero. Similarly, endOf('month') sets the date to the last day and the time to 23:59:59.999.

These methods leverage Moment.js's method chaining capability, allowing multiple operations in a single line of code. Note that Moment.js objects are mutable, meaning these methods alter the original object. If the original object is needed elsewhere, use the clone() method to create a copy first.

Formatting Options in Detail

Moment.js's format method supports various tokens for customizing output. In the example, we used "YYYY-MM-DD hh:mm", where:

For 24-hour format, replace "hh" with "HH". For example, format('YYYY-MM-DD HH:mm') outputs results like "2023-09-01 00:00". Moment.js also supports other formatting options, such as month names and weekdays; refer to the official documentation for details.

Modern Alternatives to Moment.js

Despite its power, Moment.js has drawbacks in modern JavaScript ecosystems. First, its objects are mutable, which can lead to unintended side effects. Second, it has a large file size and lacks tree-shaking support, potentially increasing bundle size. The maintainers recommend alternatives for new projects, such as:

For projects requiring legacy browser support or deep Moment.js integration, continuing with Moment.js is reasonable. However, for new projects, considering these alternatives can improve performance and maintainability.

Complete Example and Best Practices

Below is a full example of using Moment.js to get the start and end of the current month in a project:

// Import Moment.js
const moment = require('moment');

// Get the first and last day of the current month
const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
const endOfMonth = moment().endOf('month').format('YYYY-MM-DD hh:mm');

// Output the results
console.log('Start of month:', startOfMonth); // e.g., "2023-09-01 00:00"
console.log('End of month:', endOfMonth);   // e.g., "2023-09-30 23:59"

Best practices include:

Conclusion

With Moment.js's startOf and endOf methods, developers can easily retrieve the first and last day of the current month. This article provided detailed code examples and mechanistic insights to aid understanding. We also discussed Moment.js's limitations and modern alternatives, offering guidance for project decisions. By choosing the right tool based on project requirements, developers can enhance code quality and performance effectively.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.