SimpleDateFormat pattern based on locale, but forcing a 4-digit year

前端 未结 4 1608

I need to build a date format like dd/MM/yyyy. It\'s almost like DateFormat.SHORT, but contains 4 year digits.

I try to implement it with

4条回答
  •  甜味超标
    2021-02-15 17:36

    I would do it like this:

        StringBuffer buffer = new StringBuffer();
    
        Calendar date = Calendar.getInstance();
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
        FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);
    
        StringBuffer format = dateFormat.format(date.getTime(), buffer, yearPosition);
        format.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), String.valueOf(date.get(Calendar.YEAR)));
    
        System.out.println(format);
    

    Using a FieldPosition you don't really have to care about wheter the format of the date includes the year as "yy" or "yyyy", where the year ends up or even which kind of separators are used.

    You just use the begin and end index of the year field and always replace it with the 4 digit year value and that's it.

提交回复
热议问题