Summary

Localeに応じた年月の表示順序でDateTimeFormatterを作成し、カレンダータイトル文字列として表示するよう設定します。

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, Kotlin

Description

  • 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

Comment