A Comprehensive Guide to Getting Yesterday's Date with Moment.js

Dec 05, 2025 · Programming · 13 views · 7.8

Keywords: Moment.js | Date Handling | JavaScript

Abstract: This article provides an in-depth exploration of various methods to obtain yesterday's date using the Moment.js library. It begins with the basic approach moment().subtract(1, 'days'), which directly subtracts one day from the current time. Three common scenarios are then analyzed in detail: retrieving yesterday's current time, yesterday's start time, and yesterday's end time, corresponding to moment().subtract(1, 'days').toString(), moment().subtract(1, 'days').startOf('day').toString(), and moment().subtract(1, 'days').endOf('day').toString(), respectively. The article compares the native JavaScript Date object with Moment.js in date handling and demonstrates practical applications through code examples. Finally, advanced topics such as time precision and timezone handling are discussed to help developers choose the most suitable solution based on specific needs.

Basic Method for Getting Yesterday's Date with Moment.js

In JavaScript development, date handling is a common yet error-prone task. While the native JavaScript Date object is powerful, it can be cumbersome for complex date operations. Moment.js, as a popular date manipulation library, offers a more concise and robust API. Obtaining yesterday's date is a fundamental operation in date handling, and Moment.js provides intuitive methods for this purpose.

The most straightforward method is moment().subtract(1, 'days'). This returns a Moment object representing the date and time one day before the current moment. For example, if the current time is October 10, 2023, 15:30:00, moment().subtract(1, 'days') will return October 9, 2023, 15:30:00. This method is simple and effective for most scenarios requiring yesterday's date.

Detailed Analysis of Three Common Scenarios

In practical development, obtaining yesterday's date may involve different precision requirements. Below are three common scenarios and their corresponding Moment.js solutions.

Scenario 1: Getting Yesterday's Current Time

When you need to retrieve the same time point from yesterday, use moment().subtract(1, 'days').toString(). This method returns a string representation including date and time information. For example:

const yesterdayCurrent = moment().subtract(1, 'days').toString();
console.log(yesterdayCurrent); // Outputs e.g., "Tue Oct 09 2023 15:30:00 GMT+0800"

This approach preserves time accuracy and is suitable for logging or timestamp comparison scenarios.

Scenario 2: Getting Yesterday's Start Time

Sometimes, we need yesterday's start time, i.e., midnight 00:00:00. This can be achieved with moment().subtract(1, 'days').startOf('day').toString(). For example:

const yesterdayStart = moment().subtract(1, 'days').startOf('day').toString();
console.log(yesterdayStart); // Outputs e.g., "Tue Oct 09 2023 00:00:00 GMT+0800"

This method resets the time part to the start of the day, useful for date range queries or daily data statistics.

Scenario 3: Getting Yesterday's End Time

Similarly, to get yesterday's end time (i.e., 23:59:59.999), use moment().subtract(1, 'days').endOf('day').toString(). For example:

const yesterdayEnd = moment().subtract(1, 'days').endOf('day').toString();
console.log(yesterdayEnd); // Outputs e.g., "Tue Oct 09 2023 23:59:59 GMT+0800"

This is applicable for scenarios requiring the full day's time, such as deadline calculations.

Comparison with Native JavaScript

To better understand the advantages of Moment.js, let's compare it with native JavaScript implementations. Using native JavaScript to get yesterday's date typically involves multiple steps:

const today = new Date();
const yesterday = new Date(today.setDate(today.getDate() - 1));
console.log(yesterday); // Outputs a Date object

While this code works, it has several drawbacks: first, it modifies the original today object, which may cause unintended side effects; second, it returns a Date object that requires additional processing to format as a string; third, it lacks advanced features like startOf or endOf. In contrast, Moment.js methods are safer, more readable, and more feature-rich.

Practical Application Examples

Suppose we are developing a task management system that needs to query tasks completed yesterday. We can use Moment.js to build query conditions:

const yesterdayStart = moment().subtract(1, 'days').startOf('day');
const yesterdayEnd = moment().subtract(1, 'days').endOf('day');

// Simulate a database query
const tasks = [
  { id: 1, completedAt: new Date('2023-10-09T10:00:00') },
  { id: 2, completedAt: new Date('2023-10-09T22:00:00') },
  { id: 3, completedAt: new Date('2023-10-10T01:00:00') }
];

const yesterdayTasks = tasks.filter(task => {
  const taskMoment = moment(task.completedAt);
  return taskMoment.isBetween(yesterdayStart, yesterdayEnd, null, '[]');
});

console.log(yesterdayTasks.length); // Outputs 2

This example demonstrates how to combine startOf and endOf methods for precise date range filtering.

Advanced Topics: Time Precision and Timezone Handling

When handling dates with Moment.js, it's important to consider time precision and timezone issues. By default, moment() uses local time, but you can switch to UTC time with moment.utc(). For example:

const yesterdayUTC = moment.utc().subtract(1, 'days');
console.log(yesterdayUTC.toString()); // Outputs UTC time

Additionally, Moment.js supports custom time formats using the format() method:

const yesterdayFormatted = moment().subtract(1, 'days').format('YYYY-MM-DD');
console.log(yesterdayFormatted); // Outputs e.g., "2023-10-09"

This enhances output flexibility to meet various display requirements.

Summary and Best Practices

Through this discussion, we see that Moment.js offers multiple powerful and flexible methods for obtaining yesterday's date. The basic method moment().subtract(1, 'days') is suitable for simple scenarios, while startOf and endOf methods cater to more precise needs. Compared to native JavaScript, Moment.js APIs are more intuitive and safer.

In practical development, it's recommended to choose the appropriate method based on specific requirements: use startOf('day') if only the date part is needed; combine startOf and endOf for full time ranges. Also, handle timezones carefully by using moment.utc() to avoid timezone-related issues. By leveraging Moment.js effectively, developers can handle date and time tasks more efficiently and accurately.

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.