Format date without year

前端 未结 10 1522

How can create text representation of some date, that takes locale into account and contains only day and month (no year)?

Following code gives me s

10条回答
  •  长发绾君心
    2020-12-25 13:21

    Although Andrzej Pronobis's answer is very good, it doesn't work for instance with ZH local. I ended up with manual removing year from localized pattern. This function was tested for all locals for SHORT, MEDIUM, LONG and FULL formats.

    public String removeYearFromPattern(String pattern) throws IllegalArgumentException {
        int yPos = 0;
        while (yPos < pattern.length() && pattern.charAt(yPos) != 'y' && pattern.charAt(yPos) != 'Y') {
            if (pattern.charAt(yPos) == '\'') {
                yPos++;
                while (yPos < pattern.length() && pattern.charAt(yPos) != '\'') yPos++;
            }
            yPos++;
        }
        if (yPos >= pattern.length()) throw new IllegalArgumentException("Did not find year in pattern");
        String validPatternLetters = "EMd";
        // go forward
        int endPos = yPos;
        while (endPos < pattern.length() && validPatternLetters.indexOf(pattern.charAt(endPos)) == -1) {
            endPos++;
            if (endPos < pattern.length() && pattern.charAt(endPos) == '\'') {
                endPos++;
                while (endPos < pattern.length() && pattern.charAt(endPos) != '\'')
                    endPos++;
            }
        }
        if (endPos != pattern.length()) validPatternLetters += ',';
        // go backward
        int startPos = yPos;
        while (startPos >= 0 && validPatternLetters.indexOf(pattern.charAt(startPos)) == -1) {
            startPos--;
            if (startPos >= 0 && pattern.charAt(startPos) == '\'') {
                startPos--;
                while (startPos >= 0 && pattern.charAt(startPos) != '\'') startPos--;
            }
        }
        startPos++;
        String yLetters = pattern.substring(startPos, endPos);
        return pattern.replace(yLetters, " ").trim();
    }
    

    Function above can be tested by running:

    for (Locale locale : Locale.getAvailableLocales()) {
        SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.FULL, locale);
        String dfPattern = "?";
        String newPattern = "?";
        try {
            dfPattern = df.toPattern();
            newPattern = removeYearFromPattern(dfPattern);
            df.applyPattern(newPattern);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Error removing year for " + locale + ": " + e.getMessage());
        }
        Log.d(TAG, locale + ": old  " + dfPattern + "; new " + newPattern + "; result " + df.format(new Date()));
    }
    

    I know it is not as elegant as regex, but it is a little bit faster and works for all locals (if I am able to recognize).

提交回复
热议问题