Moment.js using with Browser
Moment.js is a date library for JavaScript that parses, validates, manipulates, and formats dates. In this article, we are going to see how we can use moment.js in the browser.
Approach: To be able to use moment.js in the browser you will need to include a script tag in the head tag to import the library. We can use any of the following CDNs for including Moment.js.
CDN Links:
You can visit https://cdnjs.com/libraries/moment.js and https://www.jsdelivr.com/package/npm/moment to get the CDN file link.
<script src=”https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment-with-locales.min.js”></script>
<script src=”https://cdn.jsdelivr.net/npm/moment@2.29.3/moment.min.js”></script>
The below examples will help to understand the approach for using Moment.js in the browser.
Example 1:
HTML
<!DOCTYPE html> < html > < head > < script src = "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js" > </ script > </ head > < body > < button type = "button" onclick = "clickHandler()" > Get Today! </ button > < script > function clickHandler() { alert(moment() .format('dddd, Do MMM YYYY, h:mm:ss A')) } </ script > </ body > </ html > |
Output:
Example 2:
HTML
<!DOCTYPE html> < html > < head > < script src = "https://cdn.jsdelivr.net/npm/moment@2.29.3/moment.min.js" > </ script > </ head > < body > < button type = "button" onclick = "clickHandler()" > Click Here!!! </ button > < script > function clickHandler() { let day = "2010-02-28 13:40:55" let date = moment(day); alert(date.format("DD/MM/YYYY-H:mm:ss")); } </ script > </ body > </ html > |
Output:
Reference: https://momentjs.com/docs/#/use-it/browser/
Contact Us