![]() |
MomentJS works on Date and Time Manipulation to provide a convenient way to handle, manipulate, and format dates and times in JavaScript. It simplifies common date operations such as parsing, validating, manipulating, and displaying dates. To get yesterday’s date using Moment.js, you can use various methods and approaches. Run the below command before running the code in your local system: npm i moment Using startOf() and endOf() MethodsIn this approach, we are using the startOf method to set the time to the start of the current day, and then using the set method to decrement the day by one. This gives us the date for yesterday, which is then formatted using the format method to produce a readable date string. Example: The below example uses startOf and endOf Methods to get yesterday’s date with Momentjs.
Output: Yesterday's date: 2024-07-26 Using valueOf() methodIn this approach, we are using milliseconds manipulation to calculate yesterday’s date. We first get the current date in milliseconds using the valueOf method, then subtract the equivalent of 24 hours (in milliseconds) from it. This new value is converted back into a Moment.js object and formatted to a readable date string using the format method. Example: The below example uses Milliseconds Manipulation to get yesterday’s date with Momentjs.
Output: Yesterday's date: 2024-07-26 Using subtract() MethodIn this approach, we are using the subtract() method provided by Moment.js to get yesterday’s date by subtracting one day from the current date. The resulting date is then formatted to a readable string using the format method. Example: The below example uses subtract Method to get yesterday’s date with Momentjs.
Output: Yesterday's date: 2024-07-26 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 22 |