How to use moment.js In JQuery
In this approach, we will use moment.js which provides powerful date manipulation and formatting functionalities.
Steps to Use moment.js with jQuery:
Step 1: Include moment.js Library
Add the below CDN for moment.js to use its functionality.
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js">
</script>
Step 2: Use moment.js Methods with jQuery
Once the moment.js library is included, you can use its methods with your jQuery code to manipulate dates and times as needed.
// Example: Get the current date and format it
const currentDate = moment().format('YYYY-MM-DD');
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title > Current Date and Time </ title > <!-- moment.js cdn --> < script src = "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" > </ script > <!-- jQuery cdn --> < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" > </ script > </ head > < body style = "text-align: center;" > < h1 style = "color: green;" > w3wiki </ h1 > < h2 > Hey Geek, < br /> Welcome to w3wiki!! </ h2 > < h3 > The below weekday is extracted using jQuery with moment.js </ h3 > < p id = "output" ></ p > < script > $(document).ready(() => { const currentDate = moment(); const currentWeekday = currentDate.format('dddd'); $("#output").html( "< b >Today is: " + currentWeekday + "</ b >"); }) </ script > </ body > </ html > |
Output:
How to get the Day of the Week in jQuery ?
The Date() constructor will not give the day of the week directly. It returns a number for the weekdays starting from 0 to 6. You need to implement some extra methods in jQuery to get the day of the week as listed below:
Table of Content
- Using Date.getDay() method
- Using moment.js