android.text.format.DateFormat “HH” is not recognized like with java.text.SimpleDateFormat

后端 未结 5 1055
挽巷
挽巷 2020-12-15 06:35

When I use the \"HH\" flag in android.text.format.DateFormat, it is interpreted as a literal \"HH\". But when I use java.text.SimpleDateFormat it

5条回答
  •  醉梦人生
    2020-12-15 07:27

    I understand you have accepted an answer already but just to explain this fully to you...

    From the source code for DateFormat.java...

    The format methods in this class implement a subset of Unicode UTS #35 patterns. The subset currently supported by this class includes the following format characters: acdEHhLKkLMmsyz. Up to API level 17, only adEhkMmszy were supported. Note that this class incorrectly implements k as if it were H for backwards compatibility.

    Note the part I have marked in bold.

    The source I linked to has been updated to allow the use of H but it isn't on general release yet (API 17 is the current release of Android and doesn't support H).

    Later in the source, at the stage of declaring the format character constants, there is this comment...

    /**
     * @deprecated Use a literal {@code 'H'} (for compatibility with {@link SimpleDateFormat}
     * and Unicode) or {@code 'k'} (for compatibility with Android releases up to and including
     * Jelly Bean MR-1) instead. Note that the two are incompatible.
     */
    @Deprecated
    public  static final char    HOUR_OF_DAY            =    'k';
    

    ...and later during character replacement...

    case 'H': // hour in day (0-23)
    case 'k': // hour in day (1-24) [but see note below]
    {
        int hour = inDate.get(Calendar.HOUR_OF_DAY);
        // Historically on Android 'k' was interpreted as 'H', which wasn't
        // implemented, so pretty much all callers that want to format 24-hour
        // times are abusing 'k'. http://b/8359981.
        if (false && c == 'k' && hour == 0) {
            hour = 24;
        }
        replacement = zeroPad(hour, count);
    }
    break;
    

提交回复
热议问题