androidandroid-dateutils

Specifically using DateUtils, how do I format a numeric date with no year


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?


Solution

  • 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.