tags:

views:

84

answers:

3

How can create text representation of some date, that takes locale into account and contains only day and month (no year)?

Following code gives me something like 23/09/2010

DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).format(date);

I want to get 23/09

A: 

DateFormat.SHORT specifies M/d/yy which is what you are getting. Use SimpleDateFormat and specify a pattern. For example:
     Calendar calendar = Calendar.getInstance();
     Date date;
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("M/d");

     date = calendar.getTime();
     System.out.println(simpleDateFormat.format(date));

dwb
+1  A: 

I did it this way:

DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
if (dateFormat instanceof SimpleDateFormat) {
    SimpleDateFormat simpleDateFormat = (SimpleDateFormat) dateFormat;
    String pattern = simpleDateFormat.toPattern();

    // I modified the pattern here so that dd.MM.yyyy would result to dd.MM

    simpleDateFormat.applyPattern(modifiedPattern);

    ... etc
}
fhucho
+2  A: 

You could use regex to trim off all y's and any non-alphabetic characters before and after, if any. Here's a kickoff example:

public static void main(String[] args) throws Exception {
    for (Locale locale : Locale.getAvailableLocales()) {
        DateFormat df = getShortDateInstanceWithoutYears(locale);
        System.out.println(locale + ": " + df.format(new Date()));      
    }
}

public static DateFormat getShortDateInstanceWithoutYears(Locale locale) {
    SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
    sdf.applyPattern(sdf.toPattern().replaceAll("[^\\p{Alpha}]*y+[^\\p{Alpha}]*", ""));
    return sdf;
}

You see that this snippet tests it for all locales as well. It looks to work fine for all locales here.

BalusC
Or just ask `SimpleDateFormat` to return what you want in the first place...
Grodriguez
@Gro: this isn't what the OP is asking. Replace the method by `return new SimpleDateFormat("dd/MM", locale);` and run yourself. You'll see that the locale is only used to represent day/month in localespecific language (in my case, it's only applied in Thai). Try using `MMMM` instead of `MM` and you'll see that month names are translated accordingly. It won't rearrange the pattern.
BalusC
@BalusC: You are right, sorry. I misinterpreted the question. I'm deleting my answer and upvoting yours.
Grodriguez
I did it similarly, see my answer below.
fhucho