Localeに対応した順序の年月パターンでカレンダータイトルを表示する
Total: 22
, Today: 22
, Yesterday: 0
Posted by aterai at
Last-modified:
Summary
Locale
に応じた年月の表示順序でDateTimeFormatter
を作成し、カレンダータイトル文字列として表示するよう設定します。
Screenshot

Advertisement
Source Code Examples
public static String getLocalizedPattern(Locale locale) {
// DateFormat formatter = DateFormat.getDateInstance(DateFormat.LONG, locale);
// return ((SimpleDateFormat) formatter).toLocalizedPattern();
return DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.LONG, null, Chronology.ofLocale(locale), locale);
}
public static DateTimeFormatter getLocalizedYearMonthFormatter(Locale locale) {
String localizedPattern = getLocalizedPattern(locale);
String year = find(localizedPattern, Pattern.compile("(y+)"));
String month = find(localizedPattern, Pattern.compile("(M+)"));
String pattern = isYearFirst(locale) ? year + " / " + month : month + " / " + year;
return DateTimeFormatter.ofPattern(pattern);
}
public static String find(String str, Pattern ptn) {
Matcher matcher = ptn.matcher(str);
return matcher.find() ? matcher.group(1) : "";
}
public static boolean isYearFirst(Locale locale) {
String localizedPattern = getLocalizedPattern(locale);
int yearIndex = localizedPattern.indexOf('y');
int monthIndex = localizedPattern.indexOf('M');
return yearIndex != -1 && monthIndex != -1 && yearIndex < monthIndex;
}
View in GitHub: Java, KotlinDescription
- DateTimeFormatterBuilder.getLocalizedDateTimePattern(...)メソッドを使用して指定した
Locale
固有の日付スタイル書式設定パターンを取得Java 8
以前では( (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.LONG, locale) ).toLocalizedPattern()
などで日付パターンを取得可能
- 日付パターンを年シンボル
y
、月シンボルM
で検索し、年が月より先か後かを判断してローカライズされた年と月のパターンでDateTimeFormatter
を生成 LocalDate#format(formatter.withLocale(locale))
でLocalDate
から日時を除いたローカライズ済みの年月文字列にフォーマットしてカレンダータイトルとして設定public void updateMonthView(LocalDate localDate) { currentLocalDate = localDate; Locale locale = Locale.getDefault(); DateTimeFormatter fmt = CalendarUtils.getLocalizedYearMonthFormatter(locale); monthLabel.setText(localDate.format(fmt.withLocale(locale))); monthTable.setModel(new CalendarViewTableModel(localDate)); }
Reference
- DateTimeFormatterBuilder#getLocalizedDateTimePattern(...) (Java Platform SE 8)
- java - How do I get localized date pattern string? - Stack Overflow
- ICU - International Components for Unicodeを使用して年月
DateFormat.YEAR_MONTH
のみのパターンを生成する方法などが紹介されている
- ICU - International Components for Unicodeを使用して年月
- JTableにLocaleを考慮したLocalDateを適用してカレンダーを表示する