2013-07-01 104 views
0

我需要在「EDT」時區中獲取當前時間。我獲得了當前時間並將其格式化爲「EDT」,我正在按照我的意願得到時間。但是當我試圖在「EDT」時區解析日期時,我仍然在解析日期後以「IST」格式獲取時間。我不知道我做錯了什麼。在Java中將時區轉換爲「EDT」

Date date = new Date(); 

String format = "MM/dd/yyyy hh:mm:ss Z"; 

DateFormat formatter = new SimpleDateFormat(format); 

formatter.setTimeZone(TimeZone.getTimeZone("America/New_York")); 

String dateString = formatter.format(date); 
System.out.println(dateString); 

try {  System.out.println(formatter.parse(dateString)); 
}  

catch (ParseException e) { 
    e.printStackTrace(); 
} 
+1

EDT不是時區。它是東部時區的一部分,但一年中大部分時間都沒有生效。男人的問題是,你仍然打印'Date.toString',它總是*使用系統默認時區。 「日期」值*沒有時區*。 –

+0

Calendar instance = Calendar.getInstance(TimeZone.getTimeZone(「America/New_York」)); System.out.println(instance.getTimeZone()); System.out.println(instance.getTime()); **輸出:**東部標準時間 星期一七月01 18:02:10 IST 2013 – Sarath

+0

正常「東部標準時間」是'TimeZone.toString()'的結果。 IST部分由我以前的評論解釋。 –

回答

0

java.util.Date和.Calendar類出了名的麻煩。避免它們。而是使用Joda-Time或Java 8中的java.time包(受Joda-Time的啓發)。

與java.util.Date不同,Joda-Time中的DateTime知道它自己分配的時區。如果您未能指定時區,則將分配JVM的默認時區。

您可以根據需要將其轉換爲java.util.Date對象並從中轉換爲與其他類一起使用。

java.util.Date date = new Date(); 

DateTimeZone timeZone = DateTimeZone.forID("America/New_York"); 
DateTime dateTimeNewYork = new DateTime(date, timeZone); 
DateTime dateTimeIndia = dateTimeNewYork.withZone(DateTimeZone.forID("Asia/Kolkata")); 
DateTime dateTimeUtc = dateTimeNewYork.withZone(DateTimeZone.UTC); 

調用toString方法對這些datetime對象,看慣了生成使用明智的ISO 8601標準格式的String自己的時區。您也可以在Joda-Time上使用其他格式。