Java SimpleDateFormat 和基于语言环境的格式字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1661325/
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-08-12 18:50:19  来源:igfitidea点击:

SimpleDateFormat and locale based format string

javadatelocalesimpledateformat

提问by fiskeben

I'm trying to format a date in Java in different ways based on the given locale. For instance I want English users to see "Nov 1, 2009" (formatted by "MMM d, yyyy") and Norwegian users to see "1. nov. 2009" ("d. MMM. yyyy").

我正在尝试根据给定的语言环境以不同的方式在 Java 中格式化日期。例如,我希望英语用户看到“Nov 1, 2009”(格式为“MMM d, yyyy”)和挪威用户看到“1. nov. 2009”(“d. MMM. yyyy”)。

The month part works OK if I add the locale to the SimpleDateFormat constructor, but what about the rest?

如果我将语言环境添加到 SimpleDateFormat 构造函数中,则月份部分工作正常,但其余部分呢?

I was hoping I could add format strings paired with locales to SimpleDateFormat, but I can't find any way to do this. Is it possible or do I need to let my code check the locale and add the corresponding format string?

我希望我可以将与语言环境配对的格式字符串添加到 SimpleDateFormat,但我找不到任何方法来做到这一点。是否可能或者我需要让我的代码检查语言环境并添加相应的格式字符串?

采纳答案by jarnbjo

Use DateFormat.getDateInstance(int style, Locale locale)instead of creating your own patterns with SimpleDateFormat.

使用DateFormat.getDateInstance(int style, Locale locale)而不是使用SimpleDateFormat.

回答by JuanZe

Use the style + locale: DateFormat.getDateInstance(int style, Locale locale)

使用样式 + 语言环境DateFormat.getDateInstance(int style, Locale locale)

Check http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html

检查 http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html

Run the following example to see the differences:

运行以下示例以查看差异:

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

public class DateFormatDemoSO {
  public static void main(String args[]) {
    int style = DateFormat.MEDIUM;
    //Also try with style = DateFormat.FULL and DateFormat.SHORT
    Date date = new Date();
    DateFormat df;
    df = DateFormat.getDateInstance(style, Locale.UK);
    System.out.println("United Kingdom: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.US);
    System.out.println("USA: " + df.format(date));   
    df = DateFormat.getDateInstance(style, Locale.FRANCE);
    System.out.println("France: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.ITALY);
    System.out.println("Italy: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.JAPAN);
    System.out.println("Japan: " + df.format(date));
  }
}

Output:

输出:

United Kingdom: 25-Sep-2017
USA: Sep 25, 2017
France: 25 sept. 2017
Italy: 25-set-2017
Japan: 2017/09/25

回答by redochka

SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
String formatted = dateFormat.format(the_date_you_want_here);

回答by Yaro

Localization of date string:

日期字符串的本地化:

Based on redsonic's post:

基于 redsonic 的帖子:

private String localizeDate(String inputdate, Locale locale) { 

    Date date = new Date();
    SimpleDateFormat dateFormatCN = new SimpleDateFormat("dd-MMM-yyyy", locale);       
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");


    try {
        date = dateFormat.parse(inputdate);
    } catch (ParseException e) {
        log.warn("Input date was not correct. Can not localize it.");
        return inputdate;
    }
    return dateFormatCN.format(date);
}

String localizedDate = localizeDate("05-Sep-2013", new Locale("zh","CN"));

will be like 05-九月-2013

会像05-九月-2013

回答by Abdennour TOUMI

Java8

Java8

 import java.time.format.DateTimeFormatter;         
 myDate.format(DateTimeFormatter.ofPattern("dd-MMM-YYYY",new Locale("ar")))

回答by Basil Bourque

tl;dr

tl;博士

LocalDate.now().format(
    DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM )
                     .withLocale( new Locale( "no" , "NO" ) )
)

The troublesome classes of java.util.Dateand SimpleDateFormatare now legacy, supplanted by the java.time classes.

麻烦的java.util.DateSimpleDateFormat现在是遗留的,被 java.time 类取代。

LocalDate

LocalDate

The LocalDateclass represents a date-only value without time-of-day and without time zone.

LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.

时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

DateTimeFormatter

DateTimeFormatter

Use DateTimeFormatterto generate strings representing only the date-portion or the time-portion.

使用DateTimeFormatter来生成表示只有日期部分或时间部分的字符串。

The DateTimeFormatterclass can automatically localize.

DateTimeFormatter类别可自动定位

To localize, specify:

要本地化,请指定:

  • FormatStyleto determine how long or abbreviated should the string be.
  • Localeto determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
  • FormatStyle确定字符串的长度或缩写。
  • Locale确定 (a) 用于翻译日名、月名等的人类语言,以及 (b) 决定缩写、大写、标点等问题的文化规范。

Example:

例子:

Locale l = Locale.CANADA_FRENCH ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( l );
String output = ld.format( f );

Going the other direction, you can parse a localized string.

另一方面,您可以解析本地化的字符串。

LocalDate ld = LocalDate.parse( input , f );

Note that the locale and time zone are completely orthogonal issues. You can have a Montréal moment presented in Japanese language or an Auckland New Zealand moment presented in Hindi language.

请注意,语言环境和时区是完全正交的问题。您可以用日语呈现蒙特利尔时刻,也可以用印地语呈现新西兰奥克兰时刻。

Another example: Change 6 junio 2012(Spanish) to 2012-06-06(standard ISO 8601format). The java.time classes use ISO 8601 formats by default for parsing/generating strings.

另一个示例:将6 junio 2012(西班牙语)更改为2012-06-06(标准ISO 8601格式)。java.time 类默认使用 ISO 8601 格式来解析/生成字符串。

String input = "6 junio 2012";
Locale l = new Locale ( "es" , "ES" );
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "d MMMM uuuu" , l );
LocalDate ld = LocalDate.parse ( input , f );
String output = ld.toString();  // 2012-06-06. 

Peruse formats

细读格式

Here is some example code for perusing the results of multiple formats in multiple locales, automatically localized.

这是一些示例代码,用于在多个语言环境中阅读多种格式的结果,自动本地化。

An EnumSetis an implementation of Set, highly optimized for both low memory usage and fast execution speed when collecting Enumobjects. So, EnumSet.allOf( FormatStyle.class )gives us a collection of all four of the FormatStyleenum objects to loop. For more info, see Oracle Tutorial on enum types.

AnEnumSet是 的一种实现Set,针对收集Enum对象时的低内存使用和快速执行速度进行了高度优化。因此,EnumSet.allOf( FormatStyle.class )为我们提供了FormatStyle要循环的所有四个枚举对象的集合。有关详细信息,请参阅有关枚举类型的 Oracle 教程

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 );

List < Locale > locales = new ArrayList <>( 3 );
locales.add( Locale.CANADA_FRENCH );
locales.add( new Locale( "no" , "NO" ) );
locales.add( Locale.US );

// Or use all locales (almost 800 of them, for about 120K text results).
// Locale[] locales = Locale.getAvailableLocales(); // All known locales. Almost 800 of them.

for ( Locale locale : locales )
{
    System.out.println( "------|  LOCALE: " + locale + " — " + locale.getDisplayName() + "  |----------------------------------" + System.lineSeparator() );

    for ( FormatStyle style : EnumSet.allOf( FormatStyle.class ) )
    {
        DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale );
        String output = ld.format( f );
        System.out.println( output );
    }
    System.out.println( "" );
}
System.out.println( "? fin ?" + System.lineSeparator() );

Output.

输出。

------|  LOCALE: fr_CA — French (Canada)  |----------------------------------

mardi 23 janvier 2018
23 janvier 2018
23 janv. 2018
18-01-23

------|  LOCALE: no_NO — Norwegian (Norway)  |----------------------------------

tirsdag 23. januar 2018
23. januar 2018
23. jan. 2018
23.01.2018

------|  LOCALE: en_US — English (United States)  |----------------------------------

Tuesday, January 23, 2018
January 23, 2018
Jan 23, 2018
1/23/18

? fin ?


About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Hadid Graphics

String text = new SimpleDateFormat("E, MMM d, yyyy").format(date);

回答by Mircea Stanciu

Java 8 Style for a given date

给定日期的 Java 8 样式

LocalDate today = LocalDate.of(1982, Month.AUGUST, 31);
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.ENGLISH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.FRENCH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.JAPANESE)));

回答by live-love

This will display the date according to user's current locale:

这将根据用户的当前语言环境显示日期:

To return date and time:

返回日期和时间:

import java.text.DateFormat;    
import java.util.Date;

Date date = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
String myDate = df.format(date);

Dec 31, 1969 7:00:02 PM

1969 年 12 月 31 日下午 7:00:02

To return date only, use:

要仅返回日期,请使用:

DateFormat.getDateInstance() 

Dec 31, 1969

1969 年 12 月 31 日