FileDocCategorySizeDatePackage
DateFormat.javaAPI DocAndroid 1.5 API19544Wed May 06 22:41:56 BST 2009android.text.format

DateFormat

public class DateFormat extends Object
Utility class for producing strings with formatted date/time.

This class takes as inputs a format string and a representation of a date/time. The format string controls how the output is generated.

Formatting characters may be repeated in order to get more detailed representations of that field. For instance, the format character 'M' is used to represent the month. Depending on how many times that character is repeated you get a different representation.

For the month of September:
M -> 9
MM -> 09
MMM -> Sep
MMMM -> September

The effects of the duplication vary depending on the nature of the field. See the notes on the individual field formatters for details. For purely numeric fields such as HOUR adding more copies of the designator will zero-pad the value to that number of characters.

For 7 minutes past the hour:
m -> 7
mm -> 07
mmm -> 007
mmmm -> 0007

Examples for April 6, 1970 at 3:23am:
"MM/dd/yy h:mmaa" -> "04/06/70 3:23am"
"MMM dd, yyyy h:mmaa" -> "Apr 6, 1970 3:23am"
"MMMM dd, yyyy h:mmaa" -> "April 6, 1970 3:23am"
"E, MMMM dd, yyyy h:mmaa" -> "Mon, April 6, 1970 3:23am&
"EEEE, MMMM dd, yyyy h:mmaa" -> "Monday, April 6, 1970 3:23am"
"'Noteworthy day: 'M/d/yy" -> "Noteworthy day: 4/6/70"

Fields Summary
public static final char
QUOTE
Text in the format string that should be copied verbatim rather that interpreted as formatting codes must be surrounded by the QUOTE character. If you need to embed a literal QUOTE character in the output text then use two in a row.
public static final char
AM_PM
This designator indicates whether the HOUR field is before or after noon. The output is lower-case. Examples: a -> a or p aa -> am or pm
public static final char
CAPITAL_AM_PM
This designator indicates whether the HOUR field is before or after noon. The output is capitalized. Examples: A -> A or P AA -> AM or PM
public static final char
DATE
This designator indicates the day of the month. Examples for the 9th of the month: d -> 9 dd -> 09
public static final char
DAY
This designator indicates the name of the day of the week. Examples for Sunday: E -> Sun EEEE -> Sunday
public static final char
HOUR
This designator indicates the hour of the day in 12 hour format. Examples for 3pm: h -> 3 hh -> 03
public static final char
HOUR_OF_DAY
This designator indicates the hour of the day in 24 hour format. Example for 3pm: k -> 15 Examples for midnight: k -> 0 kk -> 00
public static final char
MINUTE
This designator indicates the minute of the hour. Examples for 7 minutes past the hour: m -> 7 mm -> 07
public static final char
MONTH
This designator indicates the month of the year Examples for September: M -> 9 MM -> 09 MMM -> Sep MMMM -> September
public static final char
SECONDS
This designator indicates the seconds of the minute. Examples for 7 seconds past the minute: s -> 7 ss -> 07
public static final char
TIME_ZONE
This designator indicates the offset of the timezone from GMT. Example for US/Pacific timezone: z -> -0800 zz -> PST
public static final char
YEAR
This designator indicates the year. Examples for 2006 y -> 06 yyyy -> 2006
private static final Object
sLocaleLock
private static Locale
sIs24HourLocale
private static boolean
sIs24Hour
Constructors Summary
Methods Summary
private static final intappendQuotedText(android.text.SpannableStringBuilder s, int i, int len)

        if (i + 1 < len && s.charAt(i + 1) == QUOTE) {
            s.delete(i, i + 1);
            return 1;
        }

        int count = 0;

        // delete leading quote
        s.delete(i, i + 1);
        len--;

        while (i < len) {
            char c = s.charAt(i);

            if (c == QUOTE) {
                //  QUOTEQUOTE -> QUOTE
                if (i + 1 < len && s.charAt(i + 1) == QUOTE) {

                    s.delete(i, i + 1);
                    len--;
                    count++;
                    i++;
                } else {
                    //  Closing QUOTE ends quoted text copying
                    s.delete(i, i + 1);
                    break;
                }
            } else {
                i++;
                count++;
            }
        }

        return count;
    
public static final java.lang.CharSequenceformat(java.lang.CharSequence inFormat, java.util.Calendar inDate)
Given a format string and a {@link java.util.Calendar} object, returns a CharSequence containing the requested date.

param
inFormat the format string, as described in {@link android.text.format.DateFormat}
param
inDate the date to format
return
a {@link CharSequence} containing the requested text

        SpannableStringBuilder      s = new SpannableStringBuilder(inFormat);
        int             c;
        int             count;

        int len = inFormat.length();

        for (int i = 0; i < len; i += count) {
            int temp;

            count = 1;
            c = s.charAt(i);

            if (c == QUOTE) {
                count = appendQuotedText(s, i, len);
                len = s.length();
                continue;
            }

            while ((i + count < len) && (s.charAt(i + count) == c)) {
                count++;
            }

            String replacement;

            switch (c) {
                case AM_PM:
                    replacement = DateUtils.getAMPMString(inDate.get(Calendar.AM_PM));
                    break;
                                        
                case CAPITAL_AM_PM:
                    //FIXME: this is the same as AM_PM? no capital?
                    replacement = DateUtils.getAMPMString(inDate.get(Calendar.AM_PM));
                    break;
                
                case DATE:
                    replacement = zeroPad(inDate.get(Calendar.DATE), count);
                    break;
                    
                case DAY:
                    temp = inDate.get(Calendar.DAY_OF_WEEK);
                    replacement = DateUtils.getDayOfWeekString(temp,
                                                               count < 4 ? 
                                                               DateUtils.LENGTH_MEDIUM : 
                                                               DateUtils.LENGTH_LONG);
                    break;
                    
                case HOUR:
                    temp = inDate.get(Calendar.HOUR);

                    if (0 == temp)
                        temp = 12;
                    
                    replacement = zeroPad(temp, count);
                    break;
                    
                case HOUR_OF_DAY:
                    replacement = zeroPad(inDate.get(Calendar.HOUR_OF_DAY), count);
                    break;
                    
                case MINUTE:
                    replacement = zeroPad(inDate.get(Calendar.MINUTE), count);
                    break;
                    
                case MONTH:
                    replacement = getMonthString(inDate, count);
                    break;
                    
                case SECONDS:
                    replacement = zeroPad(inDate.get(Calendar.SECOND), count);
                    break;
                    
                case TIME_ZONE:
                    replacement = getTimeZoneString(inDate, count);
                    break;
                    
                case YEAR:
                    replacement = getYearString(inDate, count);
                    break;

                default:
                    replacement = null;
                    break;
            }
            
            if (replacement != null) {
                s.replace(i, i + count, replacement);
                count = replacement.length(); // CARE: count is used in the for loop above
                len = s.length();
            }
        }
        
        if (inFormat instanceof Spanned)
            return new SpannedString(s);
        else
            return s.toString();
    
public static final java.lang.CharSequenceformat(java.lang.CharSequence inFormat, long inTimeInMillis)
Given a format string and a time in milliseconds since Jan 1, 1970 GMT, returns a CharSequence containing the requested date.

param
inFormat the format string, as described in {@link android.text.format.DateFormat}
param
inTimeInMillis in milliseconds since Jan 1, 1970 GMT
return
a {@link CharSequence} containing the requested text

        return format(inFormat, new Date(inTimeInMillis));
    
public static final java.lang.CharSequenceformat(java.lang.CharSequence inFormat, java.util.Date inDate)
Given a format string and a {@link java.util.Date} object, returns a CharSequence containing the requested date.

param
inFormat the format string, as described in {@link android.text.format.DateFormat}
param
inDate the date to format
return
a {@link CharSequence} containing the requested text

        Calendar    c = new GregorianCalendar();
        
        c.setTime(inDate);
        
        return format(inFormat, c);
    
private static final java.lang.StringformatZoneOffset(int offset, int count)

        offset /= 1000; // milliseconds to seconds
        StringBuilder tb = new StringBuilder();

        if (offset < 0) {
            tb.insert(0, "-");
            offset = -offset;
        } else {
            tb.insert(0, "+");
        }

        int hours = offset / 3600;
        int minutes = (offset % 3600) / 60;

        tb.append(zeroPad(hours, 2));
        tb.append(zeroPad(minutes, 2));
        return tb.toString();
    
public static final java.text.DateFormatgetDateFormat(android.content.Context context)
Returns a {@link java.text.DateFormat} object that can format the date according to the current user preference.

param
context the application context
return
the {@link java.text.DateFormat} object that properly formats the date.

        String value = getDateFormatString(context);
        return new java.text.SimpleDateFormat(value);
    
public static final char[]getDateFormatOrder(android.content.Context context)
Gets the current date format stored as a char array. The array will contain 3 elements ({@link #DATE}, {@link #MONTH}, and {@link #YEAR}) in the order preferred by the user.

        char[] order = new char[] {DATE, MONTH, YEAR};
        String value = getDateFormatString(context);
        int index = 0;
        boolean foundDate = false;
        boolean foundMonth = false;
        boolean foundYear = false;

        for (char c : value.toCharArray()) {
            if (!foundDate && (c == DATE)) {
                foundDate = true;
                order[index] = DATE;
                index++;
            }

            if (!foundMonth && (c == MONTH)) {
                foundMonth = true;
                order[index] = MONTH;
                index++;
            }

            if (!foundYear && (c == YEAR)) {
                foundYear = true;
                order[index] = YEAR;
                index++;
            }
        }
        return order;
    
private static java.lang.StringgetDateFormatString(android.content.Context context)

        String value = Settings.System.getString(context.getContentResolver(),
                Settings.System.DATE_FORMAT);
        if (value == null || value.length() < 6) {
            /*
             * No need to localize -- this is an emergency fallback in case
             * the setting is missing, but it should always be set.
             */
            value = "MM-dd-yyyy";
        }
        return value;
    
public static final java.text.DateFormatgetLongDateFormat(android.content.Context context)
Returns a {@link java.text.DateFormat} object that can format the date in long form (such as December 31, 1999) based on user preference.

param
context the application context
return
the {@link java.text.DateFormat} object that formats the date in long form.

        String value = getDateFormatString(context);
        if (value.indexOf('M") < value.indexOf('d")) {
            value = context.getString(R.string.full_date_month_first);
        } else {
            value = context.getString(R.string.full_date_day_first);
        }
        return new java.text.SimpleDateFormat(value);
    
public static final java.text.DateFormatgetMediumDateFormat(android.content.Context context)
Returns a {@link java.text.DateFormat} object that can format the date in medium form (such as Dec. 31, 1999) based on user preference.

param
context the application context
return
the {@link java.text.DateFormat} object that formats the date in long form.

        String value = getDateFormatString(context);
        if (value.indexOf('M") < value.indexOf('d")) {
            value = context.getString(R.string.medium_date_month_first);
        } else {
            value = context.getString(R.string.medium_date_day_first);
        }
        return new java.text.SimpleDateFormat(value);
    
private static final java.lang.StringgetMonthString(java.util.Calendar inDate, int count)

        int month = inDate.get(Calendar.MONTH);
        
        if (count >= 4)
            return DateUtils.getMonthString(month, DateUtils.LENGTH_LONG);
        else if (count == 3)
            return DateUtils.getMonthString(month, DateUtils.LENGTH_MEDIUM);
        else {
            // Calendar.JANUARY == 0, so add 1 to month.
            return zeroPad(month+1, count);
        }
    
public static final java.text.DateFormatgetTimeFormat(android.content.Context context)
Returns a {@link java.text.DateFormat} object that can format the time according to the current user preference.

param
context the application context
return
the {@link java.text.DateFormat} object that properly formats the time.

        boolean b24 = is24HourFormat(context);
        int res;

        if (b24) {
            res = R.string.twenty_four_hour_time_format;
        } else {
            res = R.string.twelve_hour_time_format;
        }

        return new java.text.SimpleDateFormat(context.getString(res));
    
private static final java.lang.StringgetTimeZoneString(java.util.Calendar inDate, int count)

        TimeZone tz = inDate.getTimeZone();
        
        if (count < 2) { // FIXME: shouldn't this be <= 2 ?
            return formatZoneOffset(inDate.get(Calendar.DST_OFFSET) +
                                    inDate.get(Calendar.ZONE_OFFSET),
                                    count);
        } else {
            boolean dst = inDate.get(Calendar.DST_OFFSET) != 0;
            return tz.getDisplayName(dst, TimeZone.SHORT);
        }
    
private static final java.lang.StringgetYearString(java.util.Calendar inDate, int count)

        int year = inDate.get(Calendar.YEAR);
        return (count <= 2) ? zeroPad(year % 100, 2) : String.valueOf(year);
    
public static booleanis24HourFormat(android.content.Context context)
Returns true if user preference is set to 24-hour format.

param
context the context to use for the content resolver
return
true if 24 hour time format is selected, false otherwise.



                                        
         
        String value = Settings.System.getString(context.getContentResolver(),
                Settings.System.TIME_12_24);

        if (value == null) {
            Locale locale = context.getResources().getConfiguration().locale;

            synchronized (sLocaleLock) {
                if (sIs24HourLocale != null && sIs24HourLocale.equals(locale)) {
                    return sIs24Hour;
                }
            }

            java.text.DateFormat natural =
                java.text.DateFormat.getTimeInstance(
                    java.text.DateFormat.LONG, locale);

            if (natural instanceof SimpleDateFormat) {
                SimpleDateFormat sdf = (SimpleDateFormat) natural;
                String pattern = sdf.toPattern();

                if (pattern.indexOf('H") >= 0) {
                    value = "24";
                } else {
                    value = "12";
                }
            } else {
                value = "12";
            }

            synchronized (sLocaleLock) {
                sIs24HourLocale = locale;
                sIs24Hour = !value.equals("12");
            }
        }

        boolean b24 =  !(value == null || value.equals("12"));
        return b24;
    
private static final java.lang.StringzeroPad(int inValue, int inMinDigits)

        String val = String.valueOf(inValue);

        if (val.length() < inMinDigits) {
            char[] buf = new char[inMinDigits];

            for (int i = 0; i < inMinDigits; i++)
                buf[i] = '0";

            val.getChars(0, val.length(), buf, inMinDigits - val.length());
            val = new String(buf);
        }
        return val;