避免java.util.Date &日曆
你找到的衆多原因之一,以避免使用java.util.Date & .Calendar。他們是非常麻煩的。要麼使用Joda-Time,要麼在Java 8中使用受Joda-Time啓發並由JSR 310定義的新java.time package。
搜索StackOverflow for「joda date」以查找很多示例。
時區
你說:
我的時區爲GMT + 1。
不正確的,你的本地從UTC/GMT偏移是+01。那不是你的時區。時區是關於夏令時(DST)和其他異常的規則的偏移量加規則。
這偏移應該有兩個數字:+01
(或+01:00
),而不是+1
,根據ISO 8601標準。
避免3或4個字母代碼,如CET。它們既不標準也不唯一。使用proper time zone names。
一般來說,您應該在所有日期時間工作中指定時區,而不是依賴當前JVM的默認值。
在Joda-Time和java.time中,日期 - 時間對象都真正知道其分配的時區。 java.util.Date沒有時區,但似乎是因爲它的toString
在創建字符串表示時應用了默認時區,因爲您可悲地學到了難題。
示例代碼
某些代碼使用Joda-Time 2.3。
String input = "22/09/1985";
DateTimeZone timeZone = DateTimeZone.forID("Europe/Amsterdam");
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dateTime = formatter.withZone(timeZone).parseDateTime(input);
DateTime dateTimeUtcGmt = dateTime.withZone(DateTimeZone.UTC);
DateTime dateTimeIndia = dateTime.withZone(DateTimeZone.forID("Asia/Kolkata"));
String outputMontreal = DateTimeFormat.forStyle("FF").withZone(DateTimeZone.forID("America/Montreal")).withLocale(Locale.CANADA_FRENCH).print(dateTime);
// All of the above date-time represent the very same moment in the timeline of the Universe.
轉儲到控制檯...
System.out.println("dateTime: " + dateTime);
System.out.println("dateTimeUtcGmt: " + dateTimeUtcGmt);
System.out.println("dateTimeIndia: " + dateTimeIndia);
System.out.println("outputMontreal: " + outputMontreal);
運行當...
dateTime: 1985-09-22T00:00:00.000+02:00
dateTimeUtcGmt: 1985-09-21T22:00:00.000Z
dateTimeIndia: 1985-09-22T03:30:00.000+05:30
outputMontreal: samedi 21 septembre 1985 18 h 00 EDT
使用'的SimpleDateFormat( 「EEE MMM d HH:MM:SSžDD/MM/YYYY」);' –
所以它是不可能讓sdf將字符串解釋爲UTC而不定義字符串中的時區? – wutzebaer
嚴格地說,所有Date對象都基於UTC,因爲它在內部存儲爲自1970年1月1日00:00 UTC以來的毫秒數。使用第二個「DateFormat」在正確的時區顯示日期的實際文本。 – Powerlord