Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 275
Andrew Avatar asked Jan 20 '16 14:01

Andrew


People also ask

How do you format a date?

The international standard recommends writing the date as year, then month, then the day: YYYY-MM-DD.

How do you format a date in Java?

Creating A Simple Date FormatString pattern = "yyyy-MM-dd" ; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); The specified parameter “pattern” is the pattern used for formatting and parsing dates.

What date format is dd mm yyyy?

The United States is one of the few countries that use “mm-dd-yyyy” as their date format–which is very very unique! The day is written first and the year last in most countries (dd-mm-yyyy) and some nations, such as Iran, Korea, and China, write the year first and the day last (yyyy-mm-dd).

What is Java Util date format?

util. Date in yyyy-mm-dd format // Converting it into String using formatter String strDate = sm.


1 Answers

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.


like image 165
Margarita Litkevych Avatar answered Nov 15 '22 00:11

Margarita Litkevych