SimpleDateFormat模式基于语言环境,但强制使用4位数年份
我需要建立一个像dd/MM/yyyy
这样的日期格式。 它几乎像DateFormat.SHORT
,但包含4年的数字。
我尝试用它来实现它
new SimpleDateFormat("dd//MM/yyyy", locale).format(date);
但是对于美国语言环境,格式错误。
是否有一种通用的方法来格式化基于区域设置更改模式的日期?
谢谢
我会这样做:
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”,其中年份结束,甚至使用哪种分隔符。
您只需使用年份字段的开始和结束索引,并始终将其替换为4位年份值,就是这样。
java.time
这是现代的答案。 恕我直言,这些天没有人应该与长期过时的DateFormat
和SimpleDateFormat
类斗争。 他们的替代版本在2014年初的Java日期和时间API中出现了java.time类 。
我只是将这个想法应用于Happier对现代课程的回答 。
DateTimeFormatterBuilder.getLocalizedDateTimePattern
方法为Locale
生成日期和时间样式的格式设置模式。 我们操纵生成的模式字符串以强制使用4位数年份。
LocalDate date = LocalDate.of( 2017, Month.JULY, 18 ); String formatPattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern( FormatStyle.SHORT, null, IsoChronology.INSTANCE, userLocale); formatPattern = formatPattern.replaceAll("\\byy\\b", "yyyy"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern, userLocale); String output = date.format(formatter);
输出示例:
- 对于
Locale.US
。 - 适用于
UK
,FRANCE
,GERMANY
和ITALY
每一个:18/07/2017
。
DateTimeFormatterBuilder
允许我们直接获取本地化格式模式字符串,而无需先获取格式化程序,这在这里很方便。 getLocalizedDateTimePattern()
的第一个参数是日期格式样式。 null
作为第二个参数表示我们不希望包含任何时间格式。 在我的测试中,我使用了LocalDate
作为date
,但代码也适用于其他现代日期类型( LocalDateTime
, OffsetDateTime
和ZonedDateTime
)。
我有类似的方法来做到这一点,但我需要获取ui控制器的语言环境模式。
所以这是代码
// date format, always using yyyy as year display DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale); SimpleDateFormat simple = (SimpleDateFormat) dateFormat; String pattern = simple.toPattern().replaceAll("\\byy\\b", "yyyy"); System.out.println(pattern);
你能不能只使用java.text.DateFormat类?
DateFormat uk = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK); DateFormat us = DateFormat.getDateInstance(DateFormat.LONG, Locale.US); Date now = new Date(); String usFormat = us.format(now); String ukFormat = uk.format(now);
那应该做你想做的事。