Java Data Type How to - Display the year in full four digits when using localization








Question

We would like to know how to display the year in full four digits when using localization.

Answer

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
/* w w w . j  a  va  2 s  . c  o  m*/
public class Main {
  private static String setDate(int day, Locale locale) {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, +day);
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    if (df instanceof SimpleDateFormat) {
      SimpleDateFormat sdf = (SimpleDateFormat) df;
      // To show Locale specific short date expression with full year
      String pattern = sdf.toPattern().replaceAll("y+", "yyyy");
      sdf.applyPattern(pattern);
      return sdf.format(cal.getTime());
    }
    String formattedDate = df.format(cal.getTime());
    return formattedDate;
  }

  public static void main(String[] args) {
     System.out.println(setDate(1, Locale.JAPAN));
  }
}

The code above generates the following result.