![]() |
Formatting dates is essential for presenting date and time information in a way that’s readable and useful for users. Moment.js provides several methods for formatting dates from simple and predefined formats to more complex and localized representations. Below are different approaches: Table of Content Basic FormattingIn this approach we use predefined format strings to display dates in standard formats. This method is straightforward and covers common use cases. Syntax:moment().format('formatString'); Example: This demonstrates how to use the moment library in Node.js to format the current date into three different formats: YYYY-MM-DD, MM/DD/YYYY, and DD-MM-YYYY.
Output: 2024-07-26 Custom Formatting with TokensIn this approach we use custom formatting. it allows for detailed control over the date representation using tokens. Tokens represent various date components like year, month, and day. Syntax:moment().format('customFormatString'); Example: This demonstrates the use of ‘moment’ library to format and display the current date and time in two formats: MMMM Do YYYY, h:mm:ss a and dddd, MMMM Do YYYY
Output: July 26th 2024, 2:00:34 pm Localized FormattingLocalized formatting adapts date representations to various languages and regional settings. Here we need to set the locale before formatting. Syntax:moment().locale('locale').format('formatString'); Example: The code sets the locale for the `moment` library to French and German and displays the current date in a localized long format (`LL`) for each language.
Output: ![]() |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 25 |