如何在本地时刻实例上使用持续时间()?

TMG*_*TMG 1 javascript internationalization momentjs

根据moment.js 文档,您可以创建一个本地的 moment 实例,以使用全局设置之外的其他语言环境来格式化日期。

这适用于 format(),但如何在本地实例上使用 duration() 呢?

这是我尝试过的:

moment.locale('en');
var localMoment = moment("2015-03-12");
localMoment.locale('de');

// format date:
moment("2015-03-12").format("LL");        // "March 12, 2015"
localMoment.format("LL");                 // "12. März 2015"

// format duration:
moment.duration(3600000).humanize();      // "an hour"
localMoment.duration(3600000).humanize(); // TypeError: localMoment.duration is not a function
Run Code Online (Sandbox Code Playgroud)

tgo*_*tgo 5

简而言之,您不能使用localMoment.

被调用返回的 moment 对象moment()没有duration函数(无论是设置特定语言环境还是保持默认)。

duration功能属于模块本身(require调用返回的“对象” )。显然,它是这样设计的。该文件指出,持续时间无上下文,因此,没有确定的时刻。

为了得到你想要的东西,你需要做这样的事情:

moment.duration( 3600000 ).locale('de').humanize(); //eine Stunde
Run Code Online (Sandbox Code Playgroud)

语言环境仅适用于该调用:

moment.duration( 3600000 ).humanize(); //an hour
moment.duration( 3600000 ).locale('de').humanize(); //eine Stunde
moment.duration( 3600000 ).humanize(); //an hour
Run Code Online (Sandbox Code Playgroud)