moment subtract day

Moment Subtract Day

When we talk about moment subtract day, it means that we want to subtract a certain number of days from a specific date using the moment.js library.

Using Moment.js

Moment.js is a popular library that makes it easy to work with dates and times in JavaScript. To subtract a day from a specific date, we can use the subtract method provided by the moment.js library.


// Create a new moment object
var today = moment();

// Subtract one day from today's date
var yesterday = today.subtract(1, 'days');

// Output the result
console.log(yesterday.format('YYYY-MM-DD'));
// Output: 2022-11-09

In the above example, we first create a new moment object representing today's date. We then use the subtract method to subtract one day from the date. Finally, we output the result in the format of 'YYYY-MM-DD' which represents the year, month, and day in a specific format.

Using JavaScript Date Object

If you don't want to use a library like moment.js, you can still subtract a day from a specific date using the built-in JavaScript Date object.


// Create a new date object
var today = new Date();

// Subtract one day from today's date
var yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);

// Output the result
console.log(yesterday.getFullYear() + '-' + (yesterday.getMonth() + 1) + '-' + yesterday.getDate());
// Output: 2022-11-09

In the above example, we first create a new date object representing today's date. We then create a new date object that is a copy of today's date and subtract one day from it using the setDate method. Finally, we output the result in the format of 'YYYY-MM-DD'.

Conclusion

Both moment.js and the JavaScript Date object can be used to subtract a day from a specific date. Depending on your project requirements, you can choose which one to use. moment.js provides more advanced features and easier-to-read syntax, while the JavaScript Date object is built into the language and doesn't require any external dependencies.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe