One of the most common tasks in web development is formatting dates. In this blog post, we’ll learn how to format date using jQuery.
Introducing the Moment.js Library
Although jQuery itself does not provide any built-in functionality for formatting dates, we can use a popular library called Moment.js to handle date formatting. Moment.js is a lightweight, easy-to-use JavaScript library and works seamlessly with jQuery.
First, include the Moment.js library in your project by adding the following script tag in your HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Formatting Dates with Moment.js
Once you’ve included Moment.js in your project, you can start formatting dates using the various functions provided by the library. For example, you can format a date object like this:
var date = new Date(); var formattedDate = moment(date).format('MMMM Do YYYY, h:mm:ss a'); console.log(formattedDate);
In this example, we create a new date object and then use the .format() method provided by Moment.js to format the date. The formatted date string will look like this: “October 16th 2021, 10:30:45 pm”.
Using Custom Date Formats
Moment.js allows you to use custom formatting tokens in your date strings. Here are some commonly used tokens:
- MMMM – Full month name (e.g., January)
- MMM – Short month name (e.g., Jan)
- MM – Two-digit month number (e.g., 01)
- Do – Ordinal date (e.g., 1st, 2nd)
- YYYY – Four-digit year (e.g., 2021)
- YY – Two-digit year (e.g., 21)
- HH – Two-digit 24-hour time (e.g., 17 for 5 pm)
- hh – Two-digit 12-hour time (e.g., 05 for 5 pm)
- mm – Two-digit minutes (e.g., 30)
- ss – Two-digit seconds (e.g., 45)
- a – am/pm
You can combine these tokens to create custom date formats. For example, if you want to display just the month and year, you can use the following code:
var date = new Date(); var formattedDate = moment(date).format('MM/YYYY'); console.log(formattedDate);
This will output a formatted date string like “10/2021”.
Conclusion
Formatting dates in jQuery is simple and convenient with the help of the Moment.js library. With its easy-to-use and powerful date formatting functions, you can display dates in any format you desire. Now that you know how to format date in jQuery, you can start incorporating it into your projects!