SimpleDataFormat和基于区域设置的格式字符串

dkqlctbz  于 2021-07-05  发布在  Java
关注(0)|答案(10)|浏览(311)

我正在尝试根据给定的区域设置以不同的方式格式化java中的日期。例如,我希望英语用户看到“nov 1,2009”(格式为“mmm d,yyyy”),挪威用户看到“1”。2009年11月。嗯。yyyy”)。
如果我将区域设置添加到simpledateformat构造函数中,那么月份部分可以正常工作,但是其余部分呢?
我希望我可以在simpledateformat中添加与locale匹配的格式字符串,但是我找不到任何方法来实现这一点。有没有可能或者我需要让我的代码检查语言环境并添加相应的格式字符串?

e5nszbig

e5nszbig1#

给定日期的Java8样式

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

bz4sfanl2#

热释光;博士

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

麻烦的阶级 java.util.Date 以及 SimpleDateFormat 现在是遗留的,被java.time类取代。

本地日期

这个 LocalDate 类表示一个仅限日期的值,不包含一天中的时间和时区。
时区是决定日期的关键。在任何一个特定的时刻,世界各地的日期因地区而异。例如,在法国巴黎,午夜过后几分钟是新的一天,而在蒙特勒仍然是“昨天”é阿尔曲é贝克。

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

日期时间格式

使用 DateTimeFormatter 生成只表示日期部分或时间部分的字符串。
这个 DateTimeFormatter 类可以自动本地化。
要本地化,请指定: FormatStyle 确定字符串的长度或缩写。 Locale 确定(a)用于翻译日、月等名称的人类语言,以及(b)决定缩写、大写、标点等问题的文化规范。
例子:

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

相反,可以解析本地化的字符串。

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

请注意,区域设置和时区是完全正交的问题。你可以有一个月é以日语呈现的所有时刻或以印地语呈现的奥克兰-新西兰时刻。
另一个例子:改变 6 junio 2012 (西班牙语)到 2012-06-06 (标准iso 8601格式)。默认情况下,java.time类使用iso8601格式来解析/生成字符串。

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.

细读格式

下面是一些示例代码,用于在多个区域中仔细阅读多种格式的结果,并自动本地化。
EnumSet 是的实现 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() );

输出。

------|  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 »

关于java.time

java.time框架内置于Java8及更高版本中。这些类取代了旧的遗留日期时间类,例如 java.util.Date , Calendar , & SimpleDateFormat .
现在处于维护模式的joda time项目建议迁移到java.time类。
要了解更多信息,请参阅oracle教程。和搜索堆栈溢出的许多例子和解释。规格为jsr 310。
您可以直接与数据库交换java.time对象。使用符合jdbc 4.2或更高版本的jdbc驱动程序。不需要线,不需要线 java.sql.* 班级。
从哪里获得java.time类?
java se 8、java se 9及更高版本
内置的。
标准javaapi的一部分,带有一个捆绑的实现。
Java9添加了一些次要的特性和修复。
java se 6和java se 7
大部分java.time功能都是通过310个后端口后端口移植到Java6和Java7的。
安卓
android包java.time类的更高版本实现。
对于早期的android,threetenabp项目采用了threeten backport(如上所述)。了解如何使用threetenabp…。
threeten额外的项目用额外的类扩展了java.time。这个项目是java.time将来可能添加的一个试验场。您可以在这里找到一些有用的类,例如 Interval , YearWeek , YearQuarter ,等等。

ar7v8xwq

ar7v8xwq3#

使用dateformat.getdateinstance(int style,locale locale)而不是使用创建自己的模式 SimpleDateFormat .

ecfsfe2w

ecfsfe2w4#

使用style+locale:dateformat.getdateinstance(int style,locale)
检查http://java.sun.com/j2se/1.5.0/docs/api/java/text/dateformat.html
运行以下示例以查看差异:

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

输出:

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

5q4ezhmt5#

日期字符串的本地化:
根据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"));

就像05年一样-九月-2013

jbose2ul

jbose2ul6#

希望这对别人有帮助。请在下面的代码中找到接受locale示例并返回特定于locale的日期格式/模式的代码。

public static String getLocaleDatePattern(Locale locale) {
    // Validating if Locale instance is null
    if (locale == null || locale.getLanguage() == null) {
        return "MM/dd/yyyy";
    }
    // Fetching the locale specific date pattern
    String localeDatePattern = ((SimpleDateFormat) DateFormat.getDateInstance(
            DateFormat.SHORT, locale)).toPattern();
    // Validating if locale type is having language code for Chinese and country
    // code for (Hong Kong) with Date Format as - yy'?'M'?'d'?'
    if (locale.toString().equalsIgnoreCase("zh_hk")) {
        // Expected application Date Format for Chinese (Hong Kong) locale type
        return "yyyy'MM'dd";
    }
    // Replacing all d|m|y OR Gy with dd|MM|yyyy as per the locale date pattern
    localeDatePattern = localeDatePattern.replaceAll("d{1,2}", "dd")
            .replaceAll("M{1,2}", "MM")
            .replaceAll("y{1,4}|Gy", "yyyy");
    // Replacing all blank spaces in the locale date pattern
    localeDatePattern = localeDatePattern.replace(" ", "");
    // Validating the date pattern length to remove any extract characters
    if (localeDatePattern.length() > 10) {
        // Keeping the standard length as expected by the application
        localeDatePattern = localeDatePattern.substring(0, 10);
    }
    return localeDatePattern;
}
l0oc07j2

l0oc07j27#

这将根据用户的当前区域设置显示日期:
返回日期和时间:

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

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

1969年12月31日下午7:00:02
要仅返回日期,请使用:

DateFormat.getDateInstance()

1969年12月31日

iyr7buue

iyr7buue8#

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

uoifb46i9#

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

ego6inou10#

java 8

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

相关问题