In particular, using DateUtils, how do I format a numeric date without any year

I want to format the date string so that there is no year (example: "1/4").

int flags = DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_NO_YEAR;

The above flags still add a year to the date (example: "1/4/2016"). How can I cancel the year?

+4
source share
3 answers

It seems that the date formatting has changed after Android version 4.4:

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

But from version 4.4 for Android, DateUtils.formatDateRange uses libcore.icu.DateIntervalFormatstring formatting to format it.

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 preferred 12/24 format,
    // but we want to fall back to the user 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;
}

, DateFormat/SimpleDateFormat, 4.1 Android.


+3

SimpleDateFromat. - :

Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd");
String dateString = df.format(date);
+1

This works well for me

 int flags =  DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_NO_YEAR;
 String s = DateUtils.formatDateTime(this, System.currentTimeMillis(), flags);
0
source

Source: https://habr.com/ru/post/1625137/


All Articles