lil*_*ili 8 java locale simpledateformat
我需要构建一个类似的日期格式dd/MM/yyyy
.它几乎就像DateFormat.SHORT
,但包含4年的数字.
我尝试用它来实现它
new SimpleDateFormat("dd//MM/yyyy", locale).format(date);
Run Code Online (Sandbox Code Playgroud)
但是对于美国语言环境,格式错误.
是否有一种通用的方法来格式化基于区域设置更改模式的日期?
谢谢
Fra*_*ulo 13
我会这样做:
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);
Run Code Online (Sandbox Code Playgroud)
使用FieldPosition,你真的不必关心日期的格式是否包括年份为"yy"或"yyyy",其中年份结束,甚至使用哪种分隔符.
您只需使用年份字段的开始和结束索引,并始终将其替换为4位年份值,就是这样.
这里\xe2\x80\x99是现代答案。恕我直言,现在没有人应该与早已过时的事物DateFormat
和SimpleDateFormat
阶级作斗争。它们的替代品于 2014 年初在现代 Java 日期和时间 API 中出现,即java.time 类。
我只是将Happier\xe2\x80\x99s 答案中的想法应用到现代课程中。
\n\n该DateTimeFormatterBuilder.getLocalizedDateTimePattern
方法生成日期和时间样式的格式化模式Locale
。我们操纵生成的模式字符串来强制使用 4 位数年份。
LocalDate date = LocalDate.of( 2017, Month.JULY, 18 );\n\nString formatPattern =\n DateTimeFormatterBuilder.getLocalizedDateTimePattern(\n FormatStyle.SHORT, \n null, \n IsoChronology.INSTANCE, \n userLocale);\nformatPattern = formatPattern.replaceAll("\\\\byy\\\\b", "yyyy");\nDateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern, userLocale);\n\nString output = date.format(formatter);\n
Run Code Online (Sandbox Code Playgroud)\n\n输出示例:
\n\nLocale.US
:7/18/2017
。UK
、FRANCE
和GERMANY
: ITALY
。18/07/2017
DateTimeFormatterBuilder
允许我们直接获取本地化的格式模式字符串,而无需先获取格式化程序,这在这里很方便。第一个参数getLocalizedDateTimePattern()
是日期格式样式。null
第二个参数表明我们不希望包含任何时间格式。在我的测试中,我使用了LocalDate
for date
,但代码也应该适用于其他现代日期类型(LocalDateTime
、OffsetDateTime
和ZonedDateTime
)。
归档时间: |
|
查看次数: |
15237 次 |
最近记录: |