三字母時區代碼
避免使用三字母時區代碼。它們既不標準也不唯一。例如,IST
表示愛爾蘭標準時間印度標準時間和。此外,這些代碼旨在區分夏令時(DST),但這隻會讓事情混淆不清。
使用正確的descriptive time zone names來檢索包含DST和其他問題的時區對象。
喬達時間
與Java捆綁與java.util.Date & Calendar類是出了名的麻煩。避免它們。使用Joda-Time或與Java 8捆綁的新java.time。*包。
在JodaTime中,DateTime對象真正知道它自己的時區(與java.util.Date不同)。通常我們使用Joda-Time中的不可變類。因此,我們不是在DateTime對象中更改時區,而是基於舊的但具有指定的差異的DateTime對象創建新的新的對象。不同的時區可能就是這種差異。
以下是一些示例代碼。
DateTimeZone timeZone_India = DateTimeZone.forID("Asia/Kolkata");
DateTimeZone timeZone_Ireland = DateTimeZone.forID("Europe/Dublin");
DateTimeZone timeZone_US_West_Coast = DateTimeZone.forID("America/Los_Angeles");
DateTime now = new DateTime(timeZone_India);
System.out.println("now in India: " + now);
System.out.println("now in Ireland: " + now.withZone(timeZone_Ireland));
System.out.println("now in US West Coast: " + now.withZone(timeZone_US_West_Coast));
System.out.println("now in UTC/GMT: " + now.withZone(DateTimeZone.UTC));
當運行...
now in India: 2014-02-10T13:52:27.875+05:30
now in Ireland: 2014-02-10T08:22:27.875Z
now in US West Coast: 2014-02-10T00:22:27.875-08:00
now in UTC/GMT: 2014-02-10T08:22:27.875Z
的Java。時間
使用取代Joda-Time的java.time類的相同想法。
Instant
類代表UTC中的時間軸上的一個時刻,分辨率爲nanoseconds(最多九(9)位小數)。
Instant instant = Instant.now();
應用時區。
ZoneId z = ZoneId.of("America/Montreal");
ZonedDateTime zdt = instant.atZone(z);
的instant
和zdt
代表同一時刻,在時間軸上的相同點。通過不同區域的鏡頭wall-clock time可以看到每個鏡頭。
通過指定格式化模式或讓java.time自動進行本地化來生成字符串。
要本地化,指定:
例子:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(l);
String output = zdt.format(f);
你可以只使用[喬達時間](http://joda-time.sourceforge.net/)? – 2011-12-30 05:13:00