問題描述
我正在嘗試將 Calendar.getInstance(Locale l)
與指定的 Locale
一起使用,但無法正常工作.我無法弄清楚我做錯了什么.
Java 文檔.說:
<塊引用>獲取實例公共靜態(tài)日歷 getInstance(Locale aLocale)獲取使用默認時區(qū)和指定區(qū)域設(shè)置的日歷.返回的日歷基于具有給定區(qū)域設(shè)置的默認時區(qū)的當前時間.參數(shù):aLocale - 周數(shù)據(jù)的語言環(huán)境回報:日歷.
我的代碼:
public static void main (String[] args){Locale local = new Locale("pt", "BR");日歷 c = Calendar.getInstance(local);//這里我使用的是方法System.out.println(c.getTime());//在這里,我不知道為什么不工作DateFormat dt = DateFormat.getDateInstance(DateFormat.LONG, local);字符串 s = dt.format(c.getTime());System.out.println(s);//這里只是葡萄牙語巴西的一個例子}
輸出:
<塊引用>2015 年 4 月 29 日星期三 10:18:16 BRT
2015 年 4 月 29 日
第一個 print
是否應(yīng)該在葡萄牙語的 Locale("pt", "BR")
中?
Loc回答是正確的:您的電話到 Calendar::getTime
產(chǎn)生一個 java.util.Date
對象.java.util.Date
類沒有明確的時區(qū),但它的 toString
方法在生成字符串時會混淆地應(yīng)用 JVM 的當前默認時區(qū).
所有非常令人困惑的名稱和行為 - 避免這些設(shè)計不佳、令人困惑和麻煩的舊舊日期時間類的一些許多原因.相反,您應(yīng)該使用正式取代舊類的 java.time 類.
java.time
獲取 UTC 中的當前時刻.Instant
類代表時間軸上的時刻 UTC 分辨率為 納秒(最多九 (9) 位小數(shù)).
Instant instant = Instant.now();
您可以通過調(diào)用 toString
.
字符串輸出 = instant.toString();
<塊引用>
2016-09-28T19:38:21Z
問題中的代碼忽略了時區(qū)問題.當您不指定時區(qū)時,您的 JVM 當前默認時區(qū)將被隱式應(yīng)用.最好明確指定.
請注意,Locale
和時區(qū)是兩個完全不同的不同問題.
區(qū)域設(shè)置
確定 (a) 用于翻譯日期名稱、月份名稱等的人類語言,以及 (b) 決定縮寫、大寫、標點符號等問題的文化規(guī)范.- 時區(qū)決定了用于顯示日期時間值的掛鐘時間.
您可以將兩者任意組合.例如,加爾各答印度的時區(qū)具有法語語言環(huán)境,或巴西葡萄牙語言環(huán)境具有奧克蘭新西蘭時區(qū).
Locale locale = new Locale("pt", "BR");ZoneId z = ZoneId.of("太平洋/奧克蘭");
將時區(qū)應(yīng)用為 ZoneId
以生成 ZonedDateTime
.從概念上講,將其視為 ZonedDateTime = ( Instant + ZoneID )
.
以continent/region的格式指定一個正確的時區(qū)名稱代碼>.切勿使用 3-4 個字母的縮寫,例如
EST
或 IST
,因為它們不是真正的時區(qū),不是標準化的,甚至不是唯一的(!).
ZonedDateTime zdt = instant.atZone(z);
Locale
不影響表示的含義.我們可以讓 Locale
對象在通過 DateTimeFormatter
類生成表示日期時間值的字符串時驅(qū)動自動本地化.指定 FormatStyle
確定字符串的長度或縮寫.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale( 語言環(huán)境 );字符串輸出 = zdt.format( f );
轉(zhuǎn)儲到控制臺.此處看到的 instant
和 zdt
對象代表同一時刻,時間軸上的同一點.唯一的區(qū)別是通過鏡頭查看不同地區(qū)的掛鐘時間.
System.out.println("instant.toString():" + instant+ " | zdt: " + zdt+ " | 輸出:" + 輸出);
<塊引用>
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
轉(zhuǎn)化
避免使用舊的 .Date
和 .Calendar
類.但是,如果您必須將它們與尚未針對 java.time 類型更新的舊代碼一起使用,您可以進行轉(zhuǎn)換.使用添加到舊類的新方法.這里我們調(diào)用 <代碼>java.util.GregorianCalendar.from( ZonedDateTime ).
java.util.Calendar cal = java.util.GregorianCalendar.from(zdt);
然后,往另一個方向發(fā)展:
ZonedDateTime zdt = myGregorianCalendar.toZonedDateTime() ;
關(guān)于java.time
java.time框架內(nèi)置于 Java 8 及更高版本中.這些類取代了麻煩的舊日期時間類,例如 <代碼>java.util.Date, .Calendar
, &java.text.SimpleDateFormat
.
Joda-Time 項目,現(xiàn)在在 維護模式,建議遷移到 java.time.
要了解更多信息,請參閱 Oracle 教程.并在 Stack Overflow 上搜索許多示例和解釋.
大部分 java.time 功能都向后移植到 Java 6 &7 在 ThreeTen-Backport 并進一步適應(yīng) Android 在 ThreeTenABP (請參閱如何使用...).
ThreeTen-Extra 項目通過附加類擴展了 java.time.該項目是未來可能添加到 java.time 的試驗場.您可以在這里找到一些有用的類,例如 Interval
, YearWeek
, YearQuarter
和 更多.
I am trying to use Calendar.getInstance(Locale l)
with specified Locale
and is not working. I cannot figure out what I am doing wrong.
The Java Doc. say:
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.
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
Should the first print
must be in Locale("pt", "BR")
, in portuguese?
The Answer by Loc is correct: Your call to Calendar::getTime
produces a java.util.Date
object. The java.util.Date
class has no explicit time zone yet its toString
method confusingly applies the JVM’s current default time zone while generating a String.
All very confusing names and behavior - some of the many reasons 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
Get the current moment in UTC. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now();
You can create a String to represent that value with standard ISO 8601 formatting by calling toString
.
String output = instant.toString();
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.
Note that Locale
and time zone are two completely separate distinct issues.
Locale
to 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 time used to present the date-time value.
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 ZoneId
to produce a ZonedDateTime
. Conceptually, think of it as ZonedDateTime = ( Instant + ZoneID )
.
Specify a proper time zone name in the format of continent/region
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZonedDateTime zdt = instant.atZone( z );
The Locale
does not affect the meaning, on the presentation. We can let the Locale
object drive the automatic localization of when producing a String to represent the date-time value via the DateTimeFormatter
class. Specify a FormatStyle
to determine how long or abbreviated should the string be.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( locale );
String output = zdt.format( f );
Dump to console. The instant
and zdt
objects 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.
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
Conversion
Avoid the old .Date
and .Calendar
classes. 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 )
.
java.util.Calendar cal = java.util.GregorianCalendar.from( zdt ) ;
And, going the other direction:
ZonedDateTime zdt = myGregorianCalendar.toZonedDateTime() ;
About java.time
The java.time framework 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
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project 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.
這篇關(guān)于如何使用具有指定語言環(huán)境的 Calendar.getInstance的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!