如何在Angular 2类中使用moment-timezone?

use*_*541 12 javascript typescript angular

我想在课堂上使用时刻时区.这是我的打字.

"moment": "github:DefinitelyTyped/DefinitelyTyped/moment/moment.d.ts#a1575b96ec38e916750629839d2110cb96210f89",
"moment-timezone": "github:DefinitelyTyped/DefinitelyTyped/moment-timezone/moment-timezone.d.ts#f8a90040348e83926f44e690b209769c4f88b961"
Run Code Online (Sandbox Code Playgroud)

我的进口:

import * as moment from 'moment';
import * as tz from 'moment-timezone';
Run Code Online (Sandbox Code Playgroud)

我的用法:

var jun = moment("2014-06-01T12:00:00Z");
jun.tz('America/Los_Angeles').format('ha z');
Run Code Online (Sandbox Code Playgroud)

我的错误:

Property 'tz' does not exist on type 'Moment'.
Run Code Online (Sandbox Code Playgroud)

ryn*_*nop 10

使用Typescript@types包并通过它导入它import * as moment from 'moment-timezone'; 您可以使用所有moment方法和成员变量moment-timezone导出它们.

我有一个完整的例子,使用SystemJS, 如何通过SystemJs在Angular2中使用时刻 - 时区


小智 10

请尝试以下代码:

import * as moment from 'moment-timezone';

   export class Page1 {  

     public setdate = moment(); // today date
     constructor(){
       this.setdate.tz("Asia/Singapore").format('YYYY-MM-DD HH:mm:ss');
       console.log(this.setdate.tz("Asia/Singapore").format('YYYY-MM-DD HH:mm:ss'));
     }
   }
Run Code Online (Sandbox Code Playgroud)


小智 9

我有同样的问题并以这种方式解决了它:

输入(ambientDependencies):

"moment": "registry:dt/moment#2.8.0+20160316155526",
"moment-timezone": "github:DefinitelyTyped/DefinitelyTyped/moment-timezone/moment-timezone.d.ts#f8a90040348e83926f44e690b209769c4f88b961"
Run Code Online (Sandbox Code Playgroud)

进口:

import * as moment from 'moment';
import 'moment-timezone'
Run Code Online (Sandbox Code Playgroud)

用法:

moment("2014-06-01T12:00:00Z")
  .tz('America/Los_Angeles')
  .format('ha z');
Run Code Online (Sandbox Code Playgroud)

所以,基本上我正在对当前导入的对象执行.tz()函数(事实上它并不存在),但是时刻时区的导入扩展了它的附加功能.

我还使用systemjs-plugin-json在moment-timezone库中正确加载时区定义的json对象.

我希望这有帮助.


Han*_*kCa 8

我将在 2020 年更新此内容。

$ npm install moment-timezone @types/moment-timezone

import moment from 'moment-timezone';

...

// do this - outside of any class is fine    
moment.tz.add('America/Los_Angeles|PST PDT|80 70|01010101010|1Lzm0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0');


...

someMethod() {
    const m = moment(the_date);
    ...
    const mFormatted = m.tz('America/Los_Angeles').format('YYYY-MM-DDTHH:mm:ssZZ');
}
Run Code Online (Sandbox Code Playgroud)

时区定义可以在https://github.com/moment/moment-timezone/blob/develop/data/packed/latest.json找到。我用它来定义我自己的,而不是全部读进去。