views:

136

answers:

1

Hi,

In my application I am using code like this:

DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
df.setTimeZone(User.getTimeZone());
String s = df.format(d);

to format dates in an application that is used across different locales. I'd like to, sometimes, add seconds to this but I don't want to just specify one specific format using the SimpleDateFormat as I would loose the power of the locale based formatting.

So, anyone got any ideas how to make a minor change to the locale-formatted date?

Cheers,

Chris

A: 

The only straight-forward solution I have found is using FieldPosition:

DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
df.setTimeZone(User.getTimeZone());
StringBuffer sb = new StringBuffer();
FieldPosition fp = new FieldPosition(DateFormat.MINUTE_FIELD);
sb = df.format(d, sb, fp);
sb.insert( fp.getEndIndex(), new SimpleDateFormat(":ss").format(d) );
String s = sb.toString();

This is finding the position of the minute field in the string then allowing me to add the seconds straight after it. The only real problems I can see with this, apart from it being a bit ugly, is that ":" might not be the correct separator and it might already have seconds in it. So can anyone see a better answer?

cuvavu