ArticleZip > Moment Js Get Yesterday Time Range From Midnight To Midnight

Moment Js Get Yesterday Time Range From Midnight To Midnight

Are you working on a project that requires you to get yesterday's time range from midnight to midnight using Moment.js? Well, you're in the right place! In this article, we'll walk you through the steps to achieve this using Moment.js, a popular JavaScript library for parsing, validating, manipulating, and formatting dates and times.

To get yesterday's time range, we need to determine the start time of yesterday (midnight) and the end time of yesterday (just before the next midnight). Let's break it down step by step.

First, we need to create a Moment.js object for the current date and time. This can be achieved by using the following code snippet:

Javascript

const now = moment();

This code snippet initializes a Moment.js object representing the current date and time.

Next, we can subtract a day from the current date to get yesterday's date. We can then set the time to midnight using the `startOf()` function. Here's how you can do it:

Javascript

const yesterdayStart = now.clone().subtract(1, 'days').startOf('day');

In this code, we create a new Moment.js object `yesterdayStart` by cloning the `now` object, subtracting one day, and setting the time to the start of the day (midnight).

Similarly, to get the end time of yesterday (just before midnight), we can set the time to the end of the day using the `endOf()` function like this:

Javascript

const yesterdayEnd = now.clone().subtract(1, 'days').endOf('day');

Here, we create the `yesterdayEnd` object by cloning the `now` object, subtracting one day, and setting the time to the end of the day (just before midnight).

Now that we have obtained the start and end times of yesterday, we can display or use them as needed. For example, if you want to log these times, you can do so like this:

Javascript

console.log('Yesterday Start:', yesterdayStart.format('YYYY-MM-DD HH:mm:ss'));
console.log('Yesterday End:', yesterdayEnd.format('YYYY-MM-DD HH:mm:ss'));

In this snippet, we format and log the start and end times of yesterday in the desired format (YYYY-MM-DD HH:mm:ss).

By following these steps, you can easily get yesterday's time range from midnight to midnight using Moment.js in your projects. This functionality can be helpful in various applications where you need to work with dates and times effectively.

We hope this article has been informative and useful in guiding you on how to achieve this specific task using Moment.js. Feel free to experiment further with Moment.js and explore its capabilities in handling date and time-related operations efficiently. Happy coding!

×