SimpleDateFormat模式基于语言环境,但强制使用4位数年份

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位年份值,就是这样.


Ole*_*.V. 5

java.time

\n\n

这里\xe2\x80\x99是现代答案。恕我直言,现在没有人应该与早已过时的事物DateFormatSimpleDateFormat阶级作斗争。它们的替代品于 2014 年初在现代 Java 日期和时间 API 中出现,即java.time 类

\n\n

我只是将Happier\xe2\x80\x99s 答案中的想法应用到现代课程中。

\n\n

DateTimeFormatterBuilder.getLocalizedDateTimePattern方法生成日期和时间样式的格式化模式Locale。我们操纵生成的模式字符串来强制使用 4 位数年份。

\n\n
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\n
    \n
  • 为了Locale.US7/18/2017
  • \n
  • 对于每个UKFRANCEGERMANY: ITALY18/07/2017
  • \n
\n\n

DateTimeFormatterBuilder允许我们直接获取本地化的格式模式字符串,而无需先获取格式化程序,这在这里很方便。第一个参数getLocalizedDateTimePattern()是日期格式样式。null第二个参数表明我们不希望包含任何时间格式。在我的测试中,我使用了LocalDatefor date,但代码也应该适用于其他现代日期类型(LocalDateTimeOffsetDateTimeZonedDateTime)。

\n