I need to build a date format like dd/MM/yyyy
. It\'s almost like DateFormat.SHORT
, but contains 4 year digits.
I try to implement it with
I would do it like this:
StringBuffer buffer = new StringBuffer();
Calendar date = Calendar.getInstance();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);
StringBuffer format = dateFormat.format(date.getTime(), buffer, yearPosition);
format.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), String.valueOf(date.get(Calendar.YEAR)));
System.out.println(format);
Using a FieldPosition you don't really have to care about wheter the format of the date includes the year as "yy" or "yyyy", where the year ends up or even which kind of separators are used.
You just use the begin and end index of the year field and always replace it with the 4 digit year value and that's it.