【问题标题】:How to use moment-timezone in Angular 2 class?如何在 Angular 2 类中使用时刻时区?
【发布时间】:2016-05-31 08:13:44
【问题描述】:

我正在尝试在课堂上使用时刻时区。 这是我的打字。

"moment": "github:DefinitelyTyped/DefinitelyTyped/moment/moment.d.ts#a1575b96ec38e916750629839d2110cb96210f89",
"moment-timezone": "github:DefinitelyTyped/DefinitelyTyped/moment-timezone/moment-timezone.d.ts#f8a90040348e83926f44e690b209769c4f88b961"

我的导入:

import * as moment from 'moment';
import * as tz from 'moment-timezone';

我的用法:

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

我的错误:

Property 'tz' does not exist on type 'Moment'.

【问题讨论】:

    标签: javascript typescript angular


    【解决方案1】:

    我会在 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');
    }
    

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

    【讨论】:

    • 谢谢,这很有帮助。但是,我发现 latest moment-timezone 包中的 index.js 文件加载了所有最新数据。所以,自己定义是多余的。
    • 是的,但是您将不必要地加载所有这些。如果这就是您所需要的,那么添加额外的一行并不难。多出 10 行,预定义的解决方案可能会更好。
    【解决方案2】:

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

    类型(ambientDependencies):

    "moment": "registry:dt/moment#2.8.0+20160316155526",
    "moment-timezone": "github:DefinitelyTyped/DefinitelyTyped/moment-timezone/moment-timezone.d.ts#f8a90040348e83926f44e690b209769c4f88b961"
    

    进口:

    import * as moment from 'moment';
    import 'moment-timezone'
    

    用法:

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

    所以,基本上我正在对时刻导入的对象(实际上不存在)执行 .tz() 函数,但是时刻时区的导入通过附加函数扩展了它。

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

    我希望这会有所帮助。

    【讨论】:

    • 直接导入会增加约 1MB 到您的构建大小。小心
    【解决方案3】:

    请试试这个代码:

    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'));
         }
       }
    

    【讨论】:

      【解决方案4】:

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

      我有一个使用 SystemJS 的完整示例,位于 How to use moment-timezone in Angular2 via SystemJs

      【讨论】:

        猜你喜欢
        • 2016-12-05
        • 2016-01-21
        • 2020-09-06
        • 1970-01-01
        • 2017-02-12
        • 2015-06-15
        • 2018-08-30
        • 2023-04-01
        • 1970-01-01
        相关资源
        最近更新 更多