![]() |
Moment.js is a widely used JavaScript library for managing and manipulating dates and times. It simplifies complex date operations and makes it easier to work with dates in a consistent format. One common task is to extract just the date portion from a full timestamp, ignoring the time part. This is particularly useful when we want to display dates without considering specific times or when we need to perform operations based only on dates. To use Moment.js in the project, we need to install it first. Use the below command to install Moment.js. npm install moment To remove the time from a date using Moment.js we can use several approaches: Table of Content Using startOf() MethodIn this approach we will use startOf() method which sets the time to the start of the specified unit (e.g., day, month). By setting the unit to day we can effectively remove the time portion from the date. Syntax:moment(date).startOf('day'); Example: In the below example we are using the startOf() method to remove time from the date with Moment.js.
Output: 2024-07-24 Using format() MethodIn this approach we will use the format() method it allows us to specify a format string to display the date. By providing a format that excludes the time we can effectively ignore the time portion. Syntax:moment(date).format('YYYY-MM-DD'); Example: In below example we are using format() method to remove time from date with Moment.js.
Output: 2023-07-13 Using toDate() MethodIn this approach we are using the toDate() method. This method converts a Moment.js object to a native JavaScript Date object. By combining this with standard JavaScript methods we can manipulate and format the date as needed. Syntax:moment(date).toDate().toISOString().split('T')[0]; Example: In below example we are using toDate() method to remove time from date with Moment.js.
Output: 2024-07-24
|
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 21 |