問(wèn)題描述
我必須在我的 Java 應(yīng)用程序中打印 EST 時(shí)間.我已使用以下方法將時(shí)區(qū)設(shè)置為 EST:
I have to print the EST time in my Java application. I had set the time zone to EST using:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
但是當(dāng)在這個(gè)時(shí)區(qū)遵循夏令時(shí)時(shí),我的代碼沒(méi)有打印正確的時(shí)間(它打印的時(shí)間少了 1 小時(shí)).
But when the daylight savings is being followed in this timezone, my code does not print the correct time (it prints 1 hour less).
無(wú)論是否遵守夏令時(shí),如何讓代碼始終讀取正確的時(shí)間?
How to make the code work to read the correct time always, irrespective of whether the daylight savings are being observed or not?
PS:我嘗試將時(shí)區(qū)設(shè)置為 EDT,但并沒(méi)有解決問(wèn)題.
PS: I tried setting the timezone to EDT, but it doesn't solve the problem.
推薦答案
這是開(kāi)始的問(wèn)題:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
應(yīng)完全避免使用 3 個(gè)字母的縮寫(xiě),以支持 TZDB 區(qū)域 ID.EST 是東部標(biāo)準(zhǔn)時(shí)間 - 標(biāo)準(zhǔn)時(shí)間從不遵守 DST;這不是一個(gè)完整的時(shí)區(qū)名稱(chēng).它是用于時(shí)區(qū)部分的名稱(chēng).(不幸的是,我還沒(méi)有找到一個(gè)關(guān)于半時(shí)區(qū)"概念的好詞.)
The 3-letter abbreviations should be wholeheartedly avoided in favour of TZDB zone IDs. EST is Eastern Standard Time - and Standard time never observes DST; it's not really a full time zone name. It's the name used for part of a time zone. (Unfortunately I haven't come across a good term for this "half time zone" concept.)
您想要一個(gè)完整的時(shí)區(qū)名稱(chēng).例如,America/New_York
位于東部時(shí)區(qū):
You want a full time zone name. For example, America/New_York
is in the Eastern time zone:
TimeZone zone = TimeZone.getTimeZone("America/New_York");
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(zone);
System.out.println(format.format(new Date()));
這篇關(guān)于如何在 Java 中使用 TimeZone 處理夏令時(shí)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!