2017-05-31 114 views
1

我正在構建使用Moment.js和moment-timezone中的功能創建的應用程序。我需要本地化的應用程序中的日期和時間戳,所以在我使用設備的語言設置時刻的語言環境的主文件app.ts中。Moment-Timezone在全局Moment語言環境設置後使用默認語言環境

UPDATE:這裏是樣本文件的要點與補充意見 https://gist.github.com/spstratis/fa853f9750a095d4acd0d1196a285be9

app.ts

import * as moment from 'moment/min/moment-with-locales'; 

let language = appUtil.getPhoneLanguage(); 

moment.locale(language); 

// the expected locale is printed 
console.log("Moment Locale = " + moment.locale()); 

的問題是,在當我導入此實用程序模塊moment-時區,即使我已經在主文件app.ts中設置了全局時間的區域設置,它仍然默認爲'en'區域設置。

以下是我的兩個實用方法,如果moment-timezone默認爲'en',我怎麼能夠本地化相對日期字符串和月份?

我試圖添加.locale(語言環境)的時刻方法,但沒有改變任何東西。如果我導入時刻而不是瞬時時區,這對於某些方法起作用,但對任何需要使用時區實用程序的方法均失敗。

日期util.ts

import * as moment from 'moment-timezone'; 

export function dateRelativeTime(value): string { 
    let timezoneId = appCache.getTimezoneId(); 
    let localTime = _getLocalUtcDateString(value, timezoneId); 
    let dateMoment = moment(localTime, "MM/DD/YYYY hh:mm:ss A"); 
    let formatedDate = dateMoment.tz(timezoneId).fromNow(); 

    return formatedDate; 
}; 

export function localizedMonths(): ValueList { 
    let m = moment("2016"); 
    let months = new ValueList([]); 
    for (var i = 0; i < 12; i++) { 
    months.push({ ValueMember: [i + 1], DisplayMember: m.month(i).format('MMMM') }); 
    } 

    return months; 
}; 
+0

你可以用TS和兩個時刻庫設置一個要點嗎? – BogdanBiv

+0

@BogdanBiv它使用我所有的代碼? –

+3

作爲一個方面說明:你可以使用'localeData = moment.localeData(); localeData.months();'獲取本地化的月份名稱數組,請參閱文檔中的[訪問語言環境特定功能](http://momentjs.com/docs/#/i18n/locale-data/)。 – VincenzoC

回答

0

您正在輸入錯誤的時刻。不這樣做:

import * as moment from 'moment/min/moment-with-locales'; 

只是這樣做:

import * as moment from 'moment'; 

爲你使用它們(對Node.js的),它會加載單獨的語言環境,你將被共享同一時刻依賴那個時區 - 時區使用,所以您的全球區域設置將貫穿始終。

+0

這實際上是我最初導入它的方式。它雖然沒有工作。僅在導入時刻即使在設置區域設置之後。如果之後立即註銷全局語言環境,即使嘗試將其設置爲「es」 –

+0

,也會打印出「en」。此外,還嘗試過'輸入'moment/min/locales';' –

+0

您還需要導入每個本地你需要,如文檔所示。除非你在Node.js上運行它,在這種情況下,它會在你調用它們時異步加載它們。 –

0

你試過.format('')

moment.locale();   // en 
moment().format('LT'); // 6:27 PM 
moment().format('LTS'); // 6:27:51 PM 
moment().format('L'); // 05/31/2017 
moment().format('l'); // 5/31/2017 
moment().format('LL'); // May 31, 2017 
moment().format('ll'); // May 31, 2017 
moment().format('LLL'); // May 31, 2017 6:27 PM 
moment().format('lll'); // May 31, 2017 6:27 PM 
moment().format('LLLL'); // Wednesday, May 31, 2017 6:27 PM 
moment().format('llll'); // Wed, May 31, 2017 6:27 PM 

UPDATE:另外,還要確保你的時刻庫在它的一個與區域設置: https://momentjs.com/規定有兩個時刻庫,用(時刻與 - locales.js)和無區域( moment.js)。

+0

是的 - 但它仍然返回英文中的值。即使我設置了moment.locale(「es」)。在我看來,moment-timezone並不尊重在其他文件中設置的區域設置......我正在創建一個幫助更好地解釋問題的要點。 –

+0

我已經爲這個問題添加了一個要點。你會注意到我已經在我的導入中使用了與本地語言相關的時刻。 –