It is still a problem encountered at work. Generally, a date Widget is provided on the UI to allow users to select a date. The general logic is the short date mode of DateFormatter. However, on the UI, some locale formats (such as Polish) are Medium: yyyy/mm/dd, but the Short date mode of Polish locale is dd/mm/yy.
For java. text. dateFormat. parse (String source, ParsePosition pos), the default resolution is wide: even if the user input date is not input in the format required by the object, it can be parsed as a date, the resolution is successful.
However, for special locale such as Polish, In view of inconsistent formats (yyyy/mm/dd vs dd/mm/yy ), A Medium-mode string cannot be parsed using the Short date mode of the Dateformat object. If you try to parse the string, an exception is thrown.
Solution: If the Short mode fails to be parsed, use the Medium mode for parsing.
package tools;import java.text.DateFormat;import java.text.ParseException;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Locale;public class MedeiumAndShortDateFormalForAllLocale { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub List<Locale> allLocale = new ArrayList<Locale>(); System.out.println(System.getProperty("java.version")); Locale[] locales = Locale.getAvailableLocales(); allLocale = Arrays.asList(locales); Date date = new Date(); DateFormat df = null; String strDate = DateFormat.getDateInstance(DateFormat.SHORT).format(date); System.out.println(strDate); for(Locale locale : allLocale){ if(locale != null){ df = DateFormat.getDateInstance(DateFormat.SHORT, locale); } try { date = df.parse(strDate); } catch (ParseException e) { // TODO Auto-generated catch block System.out.println("Error in parsing locale with Short: " + locale + "==>" + locale.getDisplayCountry()); df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); try { date = df.parse(strDate); } catch (ParseException e1) { // TODO Auto-generated catch block System.out.println("Error in parsing locale with Medium: " + locale + "==>" + locale.getDisplayCountry()); e1.printStackTrace(); } e.printStackTrace(); }// DateFormat mediumFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); System.out.println("Medium Fromat for Today: " + locale + "=>" + locale.getCountry() + "=>" + locale.getDisplayCountry() + "=>" + df.format(date)); } }}