TypeError: moment().tz is not a function

混江龙づ霸主 提交于 2019-12-09 02:06:36

问题


When testing using jasmine, I am getting this error.

TypeError: moment.tz is not a function

My code that I try to test is

let myDate = moment().tz(undefined, vm.timeZone).format('YYYY-MM-DD'); 

回答1:


Fix

If you're using Node.js, you may accidentally be using

const moment = require('moment'); //moment

instead of

const moment = require('moment-timezone'); //moment-timezone

Also, make sure you have installed moment-timezone with

npm install moment-timezone --save

Explanation

The bug of requiring moment without timezones could occur by installing moment with require('moment'), later deciding to npm install moment-timezone, and then forgetting to update the require.




回答2:


Below code for me...

import moment from 'moment';
import 'moment-timezone';



回答3:


I've encountered this problem too. It works for years, but after a refactor, it doesn't work. As I've investigated, moment-timezone@0.5.13 depends on moment@>=2.9.0, which might be different from moment itself.

In my case, moment-timezone uses moment@2.24.0, and moment itself version is 2.18.1. Causes moment-timezone decorated wrong version of moment.

I've change yarn.lock like this:

moment-timezone@0.5.13:
  version "0.5.13"
  resolved "https://arti-dev.ss.aws.fwmrm.net/api/npm/fw-npm/moment-timezone/-/moment-timezone-0.5.13.tgz#99ce5c7d827262eb0f1f702044177f60745d7b90"
  integrity sha1-mc5cfYJyYusPH3AgRBd/YHRde5A=
  dependencies:
    moment ">= 2.9.0"

moment@2.18.1, moment@>= 2.9.0:
  version "2.18.1"
  resolved "https://arti-dev.ss.aws.fwmrm.net/api/npm/fw-npm/moment/-/moment-2.18.1.tgz#c36193dd3ce1c2eed2adb7c802dbbc77a81b1c0f"
  integrity sha1-w2GT3Tzhwu7SrbfIAtu8d6gbHA8=

moment & moment-timezone could be used substitute for each other in this case.




回答4:


For Node.js, According to the original documentation: moment js documentation

You should do

npm install moment-timezone

Then use it like this

var moment = require('moment-timezone');
moment().tz("America/Los_Angeles").format();



回答5:


Moment should be a function call. So use let myDate = moment().tz(...)

See https://momentjs.com/timezone/docs/ for more details.

EDIT

You should also ensure that you are including the timezone extension to the moment library either through the correct npm install and require (for Node) or the correct script tags (for general browser usage). See the linked documents for the libraries/scripts to include.



来源:https://stackoverflow.com/questions/47046067/typeerror-moment-tz-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!