I18N DateFormat, 巧用int干掉if else
DateFormat大家应该都知道,用起来挺麻烦的,要考虑如下问题:
1.I18N
2.带不带time
3.如何支持多种不同的Patterns
单单考虑I18N,问题很好好解决,直接调用
public final static DateFormat getDateInstance(int style)
dateformat.date.support = MM/dd/yy;MM/dd/yyyydateFormat.time.show = hh:mm
List<DateFormat> getSupportedFormats(boolean withTime) {ResourceMap rm = context.getResourceMap(getClass());String timeFormat = rm.getString("dateFormat.time.show");List<DateFormat> formats = new ArrayList<DateFormat>();for (String format : rm.getString("dateformat.date.support").split(";")) {formats.add(new SimpleDateFormat(format));formats.add(new SimpleDateFormat(format + " "+ timeFormat));}formats.add(DateFormat.getInstance());return formats;}
List<DateFormat> getSupportedFormats(boolean withTime) {ResourceMap rm = context.getResourceMap(getClass());String timeFormat = rm.getString("dateFormat.time.show");List<DateFormat> formats = new ArrayList<DateFormat>();for (String format : rm.getString("dateformat.date.support").split(";")) { if (withTime) { formats.add(new SimpleDateFormat(format + " "+ timeFormat)); formats.add(new SimpleDateFormat(format)); } else { formats.add(new SimpleDateFormat(format)); formats.add(new SimpleDateFormat(format + " "+ timeFormat)); }}formats.add(DateFormat.getInstance());return formats;}
dateformat.date.support = MM/dd/yyyy;MM/dd/yydateFormat.time.show = hh:mm
List<DateFormat> getSupportedFormats(boolean withTime) {ResourceMap rm = context.getResourceMap(getClass());String timeFormat = rm.getString("dateFormat.time.show");List<DateFormat> formats = new ArrayList<DateFormat>();// withTime = true -> date with time format will be added first. Otherwise // the date format firstint i = withTime ? 1 : 0;formats.add(DateFormat.getInstance());for (String format : rm.getString("dateformat.date.support").split(";")) {formats.add(i % 2 , new SimpleDateFormat(format));formats.add((i + 1) % 2, new SimpleDateFormat(format + " "+ timeFormat));}return formats;}
public class FormattedTextFieldFactoryTest {private static DateFormatHelper helper;@BeforeClasspublic static void init() {Locale.setDefault(Locale.US);helper = new DateFormatHelper();}public void addSupportedFormats() {List<DateFormat> list = helper.getSupportedFormats(false);assertEquals(list.size(), 5);assertEquals(list.get(0).format(createDate(2008, 10, 16)),"10/16/08");list = helper.getSupportedFormats(true);assertEquals(list.size(), 5);assertEquals(list.get(0).format(createDate(2008, 10, 16)),"10/16/08 12:00");}private Date createDate(int year, int month, int date) {GregorianCalendar cal = new GregorianCalendar();cal.clear();cal.set(Calendar.YEAR, year);cal.set(Calendar.MONTH, month - 1);cal.set(Calendar.DATE, date);return cal.getTime();}}