You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:出现TypeError: moment(...).tz is not a function错误的解决方法

Fixing 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:32:41