Format date without year

前端 未结 10 1540

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 12:55

    You could use regex to trim off all y's and any non-alphabetic characters before and after, if any. Here's a kickoff example:

    public static void main(String[] args) throws Exception {
        for (Locale locale : Locale.getAvailableLocales()) {
            DateFormat df = getShortDateInstanceWithoutYears(locale);
            System.out.println(locale + ": " + df.format(new Date()));      
        }
    }
    
    public static DateFormat getShortDateInstanceWithoutYears(Locale locale) {
        SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
        sdf.applyPattern(sdf.toPattern().replaceAll("[^\\p{Alpha}]*y+[^\\p{Alpha}]*", ""));
        return sdf;
    }
    

    You see that this snippet tests it for all locales as well. It looks to work fine for all locales here.

提交回复
热议问题