java 如何在指定的语言环境中使用 Calendar.getInstance

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

How to use Calendar.getInstance with specified Locale

javacalendar

提问by Thufir Hawat

I am trying to use Calendar.getInstance(Locale l)with specified Localeand is not working. I cannot figure out what I am doing wrong.

我正在尝试Calendar.getInstance(Locale l)与指定一起使用但Locale无法正常工作。我无法弄清楚我做错了什么。

The Java Doc. say:

Java 文档。说:

getInstance public static Calendar getInstance(Locale aLocale)Gets a calendar using the default time zone and specified locale. The Calendar returned is based on the current time in the default time zone with the given locale.Parameters: aLocale - the locale for the week data Returns: a Calendar.

getInstance public static Calendar getInstance(Locale aLocale)获取使用默认时区和指定区域设置的日历。返回的日历基于具有给定语言环境的默认时区中的当前时间。参数: aLocale - 周数据的区域设置 返回: 日历。

My code:

我的代码:

 public static void main (String[] args){

     Locale local = new Locale("pt", "BR");

     Calendar c = Calendar.getInstance(local); // here I am using the method
     System.out.println(c.getTime()); // and here, I cannot figure out why is not working


     DateFormat dt = DateFormat.getDateInstance(DateFormat.LONG, local);
     String s = dt.format(c.getTime());
     System.out.println(s); // here just a example in portuguese Brasil
 }

Output:

输出:

Wed Apr 29 10:18:16 BRT 2015

29 de Abril de 2015

2015 年 4 月 29 日星期三 10:18:16 BRT

2015 年 4 月 29 日

Should the first printmust be in Locale("pt", "BR"), in portuguese?

第一个print必须是Locale("pt", "BR"), 葡萄牙语吗?

回答by Basil Bourque

The Answer by Locis correct: Your call to Calendar::getTimeproduces a java.util.Dateobject. The java.util.Dateclass has no explicit time zone yet its toStringmethod confusingly applies the JVM's current default time zone while generating a String.

Loc回答是正确的:您调用Calendar::getTime产生一个java.util.Date对象。该java.util.Date班有没有明确的时区,但其toString方法混淆的应用JVM的当前默认时区而产生的字符串。

All very confusing names and behavior - some of the manyreasons to avoid these poorly designed, confusing, and troublesome old legacy date-time classes. Instead you should be using the java.time classes that officially supplant the old classes.

所有非常令人困惑的名称和行为 -避免这些设计不佳、令人困惑和麻烦的旧遗留日期时间类的众多原因中的一些。相反,您应该使用正式取代旧类的 java.time 类。

java.time

时间

Get the current moment in UTC. The Instantclass represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).

获取UTC 中的当前时刻。该Instant级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。

Instant instant = Instant.now();

You can create a String to represent that value with standard ISO 8601formatting by calling toString.

您可以创建一个字符串来表示与标准值ISO 8601的格式通过调用toString

String output = instant.toString();

2016-09-28T19:38:21Z

2016-09-28T19:38:21Z

The code in the Question ignores the issue of time zone. When you do not specify a time zone your JVM's current default time zone is implicitly applied. Better to specify explicitly.

问题中的代码忽略了时区问题。当您未指定时区时,将隐式应用 JVM 当前的默认时区。最好明确指定。

Note that Localeand time zone are two completely separate distinct issues.

请注意,Locale和时区是两个完全不同的问题

  • 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.
  • Time zone determines the wall-clock timeused to present the date-time value.
  • Locale确定 (a) 用于翻译日名、月名等的人类语言,以及 (b) 决定缩写、大写、标点等问题的文化规范。
  • 时区确定用于显示日期时间值的挂钟时间

You can have any combination of the two. For example, a time zone of Kolkata India with a French locale, or a Brazil Portuguese locale with an Auckland New Zealand time zone.

您可以将两者任意组合。例如,具有法国语言环境的印度加尔各答时区,或具有新西兰奥克兰时区的巴西葡萄牙语语言环境。

Locale locale = new Locale("pt", "BR");
ZoneId z = ZoneId.of( "Pacific/Auckland" );

Apply the time zone as a ZoneIdto produce a ZonedDateTime. Conceptually, think of it as ZonedDateTime = ( Instant + ZoneID ).

将时区应用为 aZoneId以生成ZonedDateTime. 从概念上讲,将其视为ZonedDateTime = ( Instant + ZoneID ).

Specify a proper time zone namein the format of continent/region. Never use the 3-4 letter abbreviation such as ESTor ISTas they are not true time zones, not standardized, and not even unique(!).

以 格式指定正确的时区名称continent/region。永远不要使用 3-4 个字母的缩写,例如ESTIST因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZonedDateTime zdt = instant.atZone( z );

The Localedoes not affect the meaning, on the presentation. We can let the Localeobject drive the automatic localization of when producing a String to represent the date-time value via the DateTimeFormatterclass. Specify a FormatStyleto determine how long or abbreviated should the string be.

Locale不影响意义上的呈现。我们可以让Locale对象在生成 String 时驱动自动定位,以通过DateTimeFormatter类来表示日期时间值。指定 aFormatStyle以确定字符串的长度或缩写。

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
                                       .withLocale( locale );
String output = zdt.format( f );

Dump to console. The instantand zdtobjects seen here represent the very same moment, the same point on the timeline. The only difference is a view through the lens of a different region's wall-clock time.

转储到控制台。这里看到的instantzdt对象代表了同一时刻,时间线上的同一点。唯一的区别是不同地区挂钟时间的视角。

System.out.println ( "instant.toString(): " + instant 
                     + " | zdt: " + zdt 
                     + " | output: " + output );

instant.toString(): 2016-09-28T20:20:38.242Z | zdt: 2016-09-29T09:20:38.242+13:00[Pacific/Auckland] | output: Quinta-feira, 29 de Setembro de 2016 09h20min38s NZDT

Instant.toString(): 2016-09-28T20:20:38.242Z | zdt: 2016-09-29T09:20:38.242+13:00[太平洋/奥克兰] | 输出:Quinta-feira, 29 de Setembro de 2016 09h20min38s NZDT

Conversion

转换

Avoid the old .Dateand .Calendarclasses. But if you must use them with old code not yet updated for the java.time types, you can convert. Use new methods added to the old classes. Here we call java.util.GregorianCalendar.from( ZonedDateTime ).

避免旧的.Date.Calendar类。但是,如果您必须将它们与尚未针对 java.time 类型更新的旧代码一起使用,则可以进行转换。使用添加到旧类的新方法。我们在这里调用java.util.GregorianCalendar.from( ZonedDateTime ).

java.util.Calendar cal = java.util.GregorianCalendar.from( zdt ) ;

And, going the other direction:

而且,走向另一个方向:

ZonedDateTime zdt = myGregorianCalendar.toZonedDateTime() ;

About java.time

关于 java.time

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

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

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

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

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

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

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backportand further adapted to Androidin ThreeTenABP(see How to use…).

大部分的java.time功能后移植到Java 6和7 ThreeTen,反向移植,并进一步用于安卓ThreeTenABP(见如何使用......)。

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 Loc

Your first print is just print Date information & Java using Default locale for this print (English)

您的第一次打印只是使用此打印的默认语言环境打印日期信息和 Java(英语)

System.out.println(c.getTime());

This print will perform: c.getTime().toString() method, and this method using Default locale (ENGLISH) - You can take a look at Date.toString() source code to see Java using Default locale.

此打印将执行: c.getTime().toString() 方法,该方法使用默认语言环境(英文) - 您可以查看 Date.toString() 源代码以了解使用默认语言环境的 Java。

That is why the output is 'Wed Apr 29 10:18:16 BRT 2015'

这就是为什么输出是“Wed Apr 29 10:18:16 BRT 2015”

If you want print output is in portuguese. You must go with Second print.

如果你想打印输出是葡萄牙语。您必须使用第二次打印。