求助:出现TypeError: moment(...).tz is not a function错误的解决方法
TypeError: moment(...).tz is not a function Hey there, let's get this sorted out—this error is super common when working with Moment.js timezones, and it's easy to fix once you know what's missing.
Why You're Seeing This Error
The core Moment.js library doesn't include timezone support out of the box. The tz() method you're trying to use is provided by the moment-timezone plugin, which you haven't added to your project yet. Your current setup only loads the base Moment.js file, so the browser can't find the tz() function.
Step-by-Step Fixes
1. Install the moment-timezone Library
Since you're using Bower, run this command in your project directory to install the plugin:
bower install moment-timezone --save
2. Update Your HTML Script References
You need to load moment-timezone after the base Moment.js script. Update your HTML to include both files:
<!-- First load core Moment.js --> <script src="bower_components/moment/moment.js"></script> <!-- Then load moment-timezone (minified version for production) --> <script src="bower_components/moment-timezone/builds/moment-timezone.min.js"></script> <!-- Optional: If you need preloaded timezone data (avoids loading it dynamically), use this instead --> <script src="bower_components/moment-timezone/builds/moment-timezone-with-data.min.js"></script>
3. Correct Your Moment.js Usage
Your current code has a syntax mistake in how you're calling tz(). You're creating a Moment instance for the current time (moment()) and then passing a timestamp to tz(), which isn't the right pattern. Here are two correct ways to do it:
Option A: Convert an existing Moment instance to the target timezone
toolFilters.filter('dateAccordingToTimeZone', function($filter) { return function(milliSeconds, timeZoneId) { if (milliSeconds == 0) { return ""; } // Create a Moment instance from the timestamp, then convert to the timezone return moment(milliSeconds).tz(timeZoneId).format('MMM d, y H:mm:ss z'); }; })
Option B: Directly create a Moment instance in the target timezone
toolFilters.filter('dateAccordingToTimeZone', function($filter) { return function(milliSeconds, timeZoneId) { if (milliSeconds == 0) { return ""; } // Use moment.tz() to create the instance directly in the desired timezone return moment.tz(milliSeconds, timeZoneId).format('MMM d, y H:mm:ss z'); }; })
Verify the Fix
After making these changes, reload your page—your timezone conversion should work without the TypeError now. Double-check that the script paths are correct (match your Bower directory structure) and that moment-timezone is loaded after Moment.js.
内容的提问来源于stack exchange,提问作者Elad Benda

