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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7796321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:29:17  来源:igfitidea点击:

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

javalocalesimpledateformat

提问by lili

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

我需要构建一个日期格式,如dd/MM/yyyy. 它几乎就像DateFormat.SHORT,但包含 4 年数字。

I try to implement it with

我尝试用

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?

有没有一种通用的方法来格式化基于语言环境改变模式的日期?

Thank you

谢谢

回答by Francisco Paulo

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.

使用 FieldPosition,您实际上不必关心日期的格式是将年份包括为“yy”还是“yyyy”,年份结束时甚至使用哪种分隔符。

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.

您只需使用年份字段的开始和结束索引,并始终将其替换为 4 位年份值,仅此而已。

回答by Ole V.V.

java.time

时间

Here's the modern answer. IMHO these days no one should struggle with the long outdated DateFormatand SimpleDateFormatclasses. Their replacement came out in the modern Java date & time API early in 2014, the java.time classes.

这是现代答案。恕我直言,如今没有人应该与过时的课程DateFormatSimpleDateFormat课程作斗争。它们的替代品出现在 2014 年初的现代 Java 日期和时间 API 中,即java.time 类

I am just applying the idea from Happier's answerto the modern classes.

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

The DateTimeFormatterBuilder.getLocalizedDateTimePatternmethod generates a formatting pattern for date and time styles for a Locale. We manipulate the resulting pattern string to force the 4-digit year.

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

Example output:

示例输出:

  • For Locale.US: 7/18/2017.
  • For each of UK, FRANCE, GERMANYand ITALY: 18/07/2017.
  • 对于Locale.US7/18/2017
  • 对于UK, FRANCE,GERMANYITALY: 中的每一个18/07/2017

DateTimeFormatterBuilderallows us to get the localized format pattern string directly, without getting a formatter first, that's convenient here. The first argument to getLocalizedDateTimePattern()is the date format style. nullas second argument indicates that we don't want any time format included. In my test I used a LocalDatefor date, but the code should work for the other modern date types too (LocalDateTime, OffsetDateTimeand ZonedDateTime).

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

回答by Happier

I have similar way to do this, but I need to get the locale pattern for the ui controller.

我有类似的方法来做到这一点,但我需要获取 ui 控制器的语言环境模式。

So here's the code

所以这是代码

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

回答by Andrew Norman

Can you not just use java.text.DateFormat class ?

你不能只使用 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);

That should do what you want to do.

那应该做你想做的事。