基于语言环境的SimpleDateFormat模式,但强制使用4位数字的年份 [英] SimpleDateFormat pattern based on locale, but forcing a 4-digit year

查看:101
本文介绍了基于语言环境的SimpleDateFormat模式,但强制使用4位数字的年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要建立一个像dd/MM/yyyy这样的日期格式.几乎类似于DateFormat.SHORT,但是包含4年的数字.

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

我尝试用

new SimpleDateFormat("dd//MM/yyyy", locale).format(date);

但是对于美国语言环境,格式是错误的.

However for US locale the format is wrong.

是否存在一种通用的格式化日期格式的方法,该日期会根据语言环境而改变?

Is there a common way to format date that changes pattern based on locale?

谢谢

推荐答案

我会这样:

    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);

使用FieldPosition时,您实际上不必关心日期的格式是否将年份包括为"yy"或"yyyy",其中年份以年结束,甚至使用哪种分隔符.

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.

您只需使用Year字段的开始和结束索引,并始终将其替换为4位数字的year值即可.

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.

这篇关于基于语言环境的SimpleDateFormat模式,但强制使用4位数字的年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆