Format date without year

This will work for Android, in case someone needs it:

int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
String monthAndDayText = DateUtils.formatDateTime(context, date, flags);

Just wanted to contribute another modification removing year from the pattern, which works well for DateFormat.MEDIUM, even in locales such as pt_PT (d 'de' MMM 'de' yyyy) or lv_LV (y. 'gada' d. MMM).

public static DateFormat getMediumDateInstanceWithoutYears()
 {
   SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.MEDIUM);
   sdf.applyPattern(sdf.toPattern().replaceAll(
       "([^\\p{Alpha}']|('[\\p{Alpha}]+'))*y+([^\\p{Alpha}']|('[\\p{Alpha}]+'))*",
       ""));
   return sdf;
 }

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
}

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.

Tags:

Java

Date