你可以试试这样的
@Test
public void formatDate() {
Date today = new Date();
SimpleDateFormat fourDigitsYearOnlyFormat = new SimpleDateFormat("yyyy");
FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);
DateFormat dateInstanceUK = DateFormat.getDateInstance(DateFormat.SHORT,
Locale.UK);
StringBuffer sbUK = new StringBuffer();
dateInstanceUK.format(today, sbUK, yearPosition);
sbUK.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(),
fourDigitsYearOnlyFormat.format(today));
System.out.println(sbUK.toString());
DateFormat dateInstanceUS = DateFormat.getDateInstance(DateFormat.SHORT,
Locale.US);
StringBuffer sbUS = new StringBuffer();
dateInstanceUS.format(today, sbUS, yearPosition);
sbUS.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(),
fourDigitsYearOnlyFormat.format(today));
System.out.println(sbUS.toString());
}
它基本上使用DateFormat#SHORT样式格式化日期,并使用FieldPosition对象捕获年份的位置。之后,您将年份替换为其四位数格式。
输出是:
13/11/2013
11/13/2013
编辑
与任何图案一起使用
StringBuffer sb = new StringBuffer();
DateFormat dateInstance = new SimpleDateFormat("yy-MM-dd");
System.out.println(dateInstance.format(today));
dateInstance.format(today, sb, yearPosition);
sb.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(),
fourDigitsYearOnlyFormat.format(today));
System.out.println(sb.toString());
输出是:
13-11-13
2013-11-13