5

I want to format a date string to not have a year (Ex: "1/4").

int flags = DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_NO_YEAR;

The above flags still append a year to the date (Ex: "1/4/2016"). How do I drop the year?

Andrew
  • 20,756
  • 32
  • 99
  • 177
  • don´t really know if it helps, but try to set the flag: DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_NO_YEAR); (with the format show date too) – Opiatefuchs Jan 20 '16 at 14:18
  • I'm getting the same result. Possibly a bug in Android 4.1? – Andrew Jan 20 '16 at 14:19
  • I read some posts about Bugs with DateUtils since 4.0 ... maybe that´s the point... – Opiatefuchs Jan 20 '16 at 14:41

3 Answers3

3

It seems that date formatting changed after 4.4 Android version:

For 4.1 Android version DateUtils.formatDateTime goes up to DateUtils.formatDateRange where the string is formatted using Formatter.

But from 4.4 Android version DateUtils.formatDateRange uses libcore.icu.DateIntervalFormat to format a String.

public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
                                        long endMillis, int flags, String timeZone) {
    // If we're being asked to format a time without being explicitly told whether to use
    // the 12- or 24-hour clock, icu4c will fall back to the locale's preferred 12/24 format,
    // but we want to fall back to the user's preference.
    if ((flags & (FORMAT_SHOW_TIME | FORMAT_12HOUR | FORMAT_24HOUR)) == FORMAT_SHOW_TIME) {
        flags |= DateFormat.is24HourFormat(context) ? FORMAT_24HOUR : FORMAT_12HOUR;
    }

    String range = DateIntervalFormat.formatDateRange(startMillis, endMillis, flags, timeZone);
    try {
        formatter.out().append(range);
    } catch (IOException impossible) {
        throw new AssertionError(impossible);
    }
    return formatter;
}

So you have to trim a resulting String or use DateFormat/SimpleDateFormat to remove year field on 4.1 Android.


Margarita Litkevych
  • 2,086
  • 20
  • 28
2

This works well for me

 int flags =  DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_NO_YEAR;
 String s = DateUtils.formatDateTime(this, System.currentTimeMillis(), flags);
Hemix
  • 303
  • 3
  • 12
0

Try using a SimpleDateFromat. Something like this:

Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd");
String dateString = df.format(date);
DadoZolic
  • 177
  • 7