Javascript 如何通过传递缩写来获取时区?
我使用Momentjs,现在我通过以下步骤获得日期和时间Javascript 如何通过传递缩写来获取时区?,javascript,angularjs,momentjs,Javascript,Angularjs,Momentjs,我使用Momentjs,现在我通过以下步骤获得日期和时间 var TimeZone = moment.tz("Asia/Kolkata").format('LLLL'); 但我需要通过传递缩写来获取时间和日期 var TimeZone = moment.tz("IST").format('LLLL'); 我怎样才能做到这一点呢?我不知道Momentjs,但我可以提供u-JS解决方案来做同样的事情。 正如我从您的问题中了解到的,.tz方法只接受完整的时区名称,而不接受缩写形式。所以你可以使用
var TimeZone = moment.tz("Asia/Kolkata").format('LLLL');
但我需要通过传递缩写来获取时间和日期
var TimeZone = moment.tz("IST").format('LLLL');
我怎样才能做到这一点呢?我不知道Momentjs,但我可以提供u-JS解决方案来做同样的事情。 正如我从您的问题中了解到的,.tz方法只接受完整的时区名称,而不接受缩写形式。所以你可以使用JS原型继承来实现这个结果。 你要做的是用dictionary对象创建另一个你自己的方法,并用你的特性扩展矩对象。请参阅代码:
var tzMap = {
"IST" : "Asia/Kolkata",
"UST" : "America/LA" // this I only took for example i don't know it exist
or not
}
moment.__proto__.timezone = function(tzStr){
if(Object.hasOwnProperty(tzStr)){
tzStr = tzMap[tzStr];
}
return this.tz(tzStr);
}
// now instead of using
// moment.tz("Asia/Kolkata").format('LLLL');
// U can use
var TimeZone = moment.timezone("Asia/Kolkata").format('LLLL');
// or
var TimeZone = moment.timezone("IST").format('LLLL');