![]() |
VOOZH | about |
Using Moment.js to change date format in jQuery involves importing the Moment.js library and utilizing its functions to parse, manipulate, and format dates. You can easily convert dates into various formats by calling moment(date).format(desiredFormat) to display the date in your preferred format.
moment() Function: The moment() function is used to create a moment from a string.
Syntax:
moment(String);Parameter: It accepts a String as a parameter
Return Value: It returns the moment object.
format() Function: The moment().format() function is used to format the date. The format can be provided in string form which is passed as a parameter to this method.
Syntax:
moment().format(String);Parameters: This function accepts a single parameter of string type, which defines the format.
Return Value: This function returns the date.
CDN Links:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
Approach:
moment($("#date_val").val()).format('DD-MM-YYYY'); Formatting tokens for dates:
| Token | Description | Example |
| YYYY | 4-digit year | 2022 |
| YY | 2-digit year | 22 |
| MMMM | Full-length month | March |
| MMM | 3 character month | Mar |
| MM | The month of the year, zero-padded | 03 |
| M | The month of the year | 3 |
| DD | Day of the month, zero-padded | 02 |
| D | Day of the month | 2 |
| Do | Day of the month with numeric ordinal contraction | 2nd |
Example: In this example we use Moment.js and jQuery to convert and display a selected date in three different formats. When the button is clicked, the date is reformatted into various patterns and displayed dynamically.
Output: