如何使用ECMAScript Internationalization API获取所有长月名称的列表?
例如,如果用户的区域设置为assertThat(localRepository.hasLocalStorage(), is(result));
,我想获得以下内容:
@Test
void name2() throws Exception {
final Object obj = new Object();
Single<Object> just1 = Single.just(obj);
Single<Object> just2 = Single.just(obj);
Object value1 = just1.toBlocking().value();
Object value2 = just2.toBlocking().value();
assertThat(value1).isEqualTo(value2);
}
答案 0 :(得分:3)
这应该这样做:
function getMonthsForLocale(locale) {
var format = new Intl.DateTimeFormat(locale, { month: 'long' })
var months = []
for (var month = 0; month < 12; month++) {
var testDate = new Date(Date.UTC(2000, month, 1, 0, 0, 0));
months.push(format.format(testDate))
}
return months;
}
答案 1 :(得分:1)
/**
* Return list of months
* ? localeName : name of local, f.e. en-GB, default es-MX
* ✅ monthFormat : short, numeric, long (Default)
*/
function monthsForLocale(localeName = 'es-MX', monthFormat = 'long') {
const format = new Intl
.DateTimeFormat(localeName, {month: monthFormat}).format;
return [...Array(12).keys()]
.map((m) => format(new Date(Date.UTC(2021, m))));
}
// testing...
console.log(monthsForLocale());
// return ['diciembre', 'enero', ..., 'noviembre' ]
console.log(monthsForLocale('en-GB', 'numeric'));
// return // ['12', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
console.log(monthsForLocale('en-GB', 'short'));
// // ['Dec', 'Jan', 'Feb','Mar', 'Apr', 'May','Jun', 'Jul', 'Aug','Sep', 'Oct', 'Nov' ]
console.log(monthsForLocale('ja-JP', 'short'));
// // ['12月', '1月', '2月', '3月', '4月', '5月','6月', '7月', '8月','9月', '10月', '11月']
答案 2 :(得分:0)
要在Safari上也能正常运行,我们需要再增加一天的时间 (Dates in Safari appear off by one using Intl.DateTimeFormat with en-US locale)。这在我们的用例中有效,因为我们只是获取月份名称,因此从月份的第一天还是第二天生成字符串都没有关系。
const SAFARI_OFFSET_FIX = 1;
const getMonthsForLocale = (locale = navigator.language) => {
const format = new Intl.DateTimeFormat(locale, { month: 'long' });
const months = [];
for (let month = 0; month < 12; month++) {
const testDate = new Date(0, month, 1 + SAFARI_OFFSET_FIX, 0, 0, 0);
months.push(format.format(testDate));
}
return months;
};