Using Moment in  Angular/TypeScript

Quickly get Moment & Moment Timezone working in an Angular CLI TypeScript project.

Using Moment in a TypeScript Angular app is easier than you think. Here are the steps you’ll need to take to get it setup.

Basic Moment Usage

Run the following commands inside your Angular CLI project to install Moment and it’s corresponding interfaces.

npm i -S moment;
npm i -D @types/moment;

Once this is done you can work with moment objects in your application like this:

import * as moment from 'moment';

moment() will now be available in your TypeScript Angular application. If you want to support more advanced usage scenarios, continue reading.

Possible Issues

If the above approach doesn’t work for you then you can try one of the following approaches, which may solve your issue. If you don’t know what version of TypeScript you current have installed you can check with the tsc -v command.

For Typescript 2.x

You’ll want to be working with the node module resolution pattern, so make sure you have the following in your tsconfig.json file:

{
  ...
  "compilerOptions": {
    ...
    "moduleResolution": "node",
    ...
  }
}

For Typescript 1.x

You’ll need support for synthetic default imports, so make sure you have the following in your tsconfig.json file:

{
  ...
  "compilerOptions": {
    ...
    "allowSyntheticDefaultImports": true,
    ...
  }
}

Generally speaking, these are the common caused of issues with the import syntax. If you have different issues feel free to ask a question in the comments below.

Moment with Timezone Support

If you have an international audience and need to convert or otherwise work with dates and times that span various timezones you’ll want to include support for Moment Timezone, or moment.tz. This is provided by the moment-timezone package, and requires a slightly different approach to work with in an Angular or TypeScript application.

npm i -S moment moment-timezone;
npm i -D @types/moment @types/moment-timezone;

Once this is done you’ll need to work with moment objects in your application like this:

import * as moment from 'moment-timezone';

Moment Timezone extends the core Moment class, so when you include moment-timezone as a replacement for the main module you’ll still have access to all of the functionality that’s part of the main library. Including moment-timezone just provides additional helper methods for working with timezones, most of which are nested under the moment.tz.* object.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.