特别是使用 DateUtils,如何格式化没有年份的数字日期

And*_*rew 5 android android-dateutils

我想将日期字符串格式化为没有年份(例如:“1/4”)。

int flags = DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_NO_YEAR;
Run Code Online (Sandbox Code Playgroud)

上述标志仍然在日期后附加一年(例如:“1/4/2016”)。怎么降年?

Mar*_*ych 3

Android 4.4 版本后日期格式似乎发生了变化:

对于 4.1 Android 版本,DateUtils.formatDateTime上升到DateUtils.formatDateRange,其中使用 Formatter 对字符串进行格式化。

但从 Android 4.4 版本开始,DateUtils.formatDateRange用于libcore.icu.DateIntervalFormat格式化字符串。

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;
}
Run Code Online (Sandbox Code Playgroud)

因此,您必须修剪结果字符串或使用 DateFormat/SimpleDateFormat 删除 4.1 Android 上的年份字段。