5

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

int flags = DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_NO_YEAR;

上述标志仍会在日期后附加年份(例如:“1/4/2016”)。我如何删除年份?

4

3 回答 3

3

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

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

但从 4.4 Android 版本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;
}

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


于 2016-01-20T14:43:08.353 回答
2

这对我很有效

 int flags =  DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_NO_YEAR;
 String s = DateUtils.formatDateTime(this, System.currentTimeMillis(), flags);
于 2016-01-20T14:17:38.657 回答
0

尝试使用 SimpleDateFromat。像这样的东西:

Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd");
String dateString = df.format(date);
于 2016-01-20T14:21:31.767 回答