node.jsangularangular2-directivesangular-moment

How to Include moment-timezone in Angular 2 App


I realize, this question is repeated but previous once does not provide apt answer moment package was already installed

1.Installed package

npm install moment-timezone --save

Inside node_modules directory
|
|--moment
|--moment-timezone

directories present

2. Index.html included script

<script src="node_modules/moment-timezone/moment-timezone.js"></script>

System.config.js

  var map = {
    'moment':             'node_modules/moment',
    'momentzone':         'node_modules/moment-timezone'
  };
  var packages = {
    'moment':             { defaultExtension: 'js' },
    'momentzone':         { defaultExtension: 'js' }
  };

3.Inside component.ts file

import * as moment from 'moment/moment';

export class TimeComponent implements OnInit{
   ngOninit(){
         console.log(moment("2014-06-01T12:00:00Z").tz('America/Los_Angeles').format('ha z'));

   }
}

What should be imported to prevent error Property tz does not exist on type 'Moment'


Solution

  • This might help.

    Run Following command for angular-cli or npm install.

    sudo npm install moment moment-timezone --save
    npm install @types/moment @types/moment-timezone --save-dev

    for npm systemjs.config.js

       map: {
            'moment': 'npm:moment',
            'moment-timezone': 'npm:moment-timezone/builds'
          }
    packages: { 
          'moment': {
              main: './moment.js',
              defaultExtension: 'js'
           },
          'moment-timezone': {
            main: './moment-timezone-with-data-2010-2020.min.js',
            defaultExtension: 'js'
          }
    }
    

    where ever you want to use time-zone in .ts file

    import * as moment from 'moment-timezone';
    
    @Component({
      selector: 'my-app',
      template: `<h1>Hello {{name}}</h1>`,
    })
    
    export class AppComponent {    
      name = 'Angular';
      jun = moment();// creating obj.
      constructor() {
        this.jun.tz('America/Los_Angeles').format('hh : mm : ss a z');
        console.log(this.jun.tz('America/Los_Angeles').format('hh : mm : ss a z'));
        console.log(moment.tz.names()); // for all time zone.
      }