如何在HTML中为现有变量应用moment.js?能否用指定变量转换日期为moment.js格式?
Hey there! Let's walk through how to integrate moment.js with your existing Date variables, and answer your questions clearly.
1. How to apply moment.js to your existing variables in HTML
First, you need to include the moment.js library in your HTML page. You can either download the library file and host it locally, or use a CDN to load it. Add this script tag before your custom JavaScript code (usually right before the closing </body> tag):
<script src="path/to/moment.min.js"></script>
Once moment.js is loaded, you can easily convert your existing Date objects (x and y) into moment.js objects by passing them directly into the moment() function. From there, you can use all of moment.js's powerful formatting and manipulation features.
Here's a full example that modifies your original code to use moment.js:
<!DOCTYPE html> <html> <body> <script src="path/to/moment.min.js"></script> <script> // Your original Date variables var x = new Date(document.lastModified); var y = new Date(); // Convert Date objects to moment.js objects const lastModifiedMoment = moment(x); const currentMoment = moment(y); // Format and display the dates using moment.js document.writeln('The last modified date is: ' + lastModifiedMoment.format('YYYY-MM-DD HH:mm:ss') + ' and current date is: ' + currentMoment.format('YYYY-MM-DD HH:mm:ss')); </script> </body> </html>
format('YYYY-MM-DD HH:mm:ss')is just one example—you can customize the format string to match your needs (like'MM/DD/YYYY'or'ddd, MMM Do YYYY').
2. Can you convert the current date/time to moment.js format using these variables?
Absolutely! Your y variable is already a Date object for the current time. As shown above, passing it into moment(y) immediately converts it into a moment.js object. This object gives you access to all of moment.js's functionality:
- Formatting the date into any string format you want
- Adding/subtracting time (e.g.,
currentMoment.add(7, 'days')to get the date in a week) - Comparing dates (e.g.,
lastModifiedMoment.isBefore(currentMoment)which will always be true here) - Extracting specific parts of the date (e.g.,
currentMoment.hour()to get the current hour)
For a quick example of using the converted moment object:
// Get current time in a human-readable format const friendlyCurrentDate = currentMoment.format('dddd, MMMM Do YYYY, h:mm:ss a'); console.log('Current time:', friendlyCurrentDate);
内容的提问来源于stack exchange,提问作者Floriane Shala

