简体   繁体   中英

How do I import moment.js?

I would like to get the correct local time of the user on my website, but I noticed that the new Date constructor does not account for the timezone. I discovered Moment.js , which allows me to get the correct local time in the browser development console when i issue moment().format(); , but not in my actual JavaScript file.

I have included the Moment.js file in my HTML document <script src="js/moment-with-locales.js"></script> , but have not imported it in my JavaScript file. How do i import the Moment.js functionality into my JavaScript file so that I can run console.log(moment().format()); without an error?

You just need to load the script before your script in the html like this:

<head>
    <!-- The momentjs library -->
    <script src="js/moment-with-locales.js"></script>
    <!-- Your javascript -->
    <script src="js/my-custom-script.js"></script>
</head>

Then in your script you can use momentjs.

moment.utc('2018-01-01 23:45:55').local().format()

If you have to use it directly in your HTML file, do

<script>
moment().format();
</script>

If you have to use it in a different javascript file (rendered on the browser as a script src in the app HTML), you can use include it using webpack.

Thanks Sriram

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM