問題描述
我正在尋找一種方法來根據用戶輸入獲取不同時區的當前時間.我知道我可以使用 Joda Time!但這是唯一的方法嗎?
I was looking for a way to get current time in various timezones based on an user input. I know I could use Joda Time! but is that the only way?
在 Java 中沒有這樣做的選項嗎?我嘗試了以下代碼,它為所有 3 個系統輸出提供了相同的輸出.
Isn't there an option in Java for doing this? I tried the following code which gives the same output for all 3 sysouts.
Calendar pst = Calendar.getInstance(TimeZone.getTimeZone("PST"));
System.out.println("PST " + pst.getTime());
Calendar ist = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println("IST " + ist.getTime());
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("Etc/UTC"));
System.out.println("UCT " + utc.getTime());
我在這里缺少什么來獲取其他時區的當前時間?
What am I missing here to get current time in other timezones?
推薦答案
是的,這將在每種情況下(或相隔毫秒)顯示相同的值,因為三個日歷都引用相同的即時 (盡管有執行時間),這就是 java.util.Date
所代表的全部內容.這是 Calendar.getTime()
的結果.
Yes, that would show the same value in every case (or milliseconds apart) because the three calendars all refer to the same instant in time (execution time notwithstanding) and that's all that a java.util.Date
represents. That's the result of Calendar.getTime()
.
但是,Calendar
本身確實知道時區,這將在您使用 Calendar.get
等時反映出來.它將也在您使用 SimpleDateFormat
時使用,您可以在其中指定特定時區.
However, the Calendar
itself does know about time zones, and that will be reflected when you use Calendar.get
etc. It will also be used when you use a SimpleDateFormat
, where you can specify a particular time zone.
// Specify whatever format you want - bear in mind different locales etc
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(calendar.getTimeZone());
String text = format.format(calendar.getTime());
目前尚不清楚您要做什么,但基本上您需要知道哪些類型是時區感知的,哪些不是.了解 java.util.Date
沒有格式、日歷系統或時區非常重要:它只是自 Unix 以來的毫秒數紀元.
It's not clear exactly what you're trying to do, but basically you need to be aware of which types are time zone aware, and which aren't. It's really important to understand that a java.util.Date
doesn't have a format, a calendar system or a time zone: it's just the number of milliseconds since the Unix epoch.
這篇關于在 Java 中使用各種日歷時區(不使用 Joda Time)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!