2013-04-15 38 views
-2

我試圖將UTC日期/時間字符串轉換爲另一個時區。它只顯示UTC時區的日期/時間。下面無法將UTC的日期轉換爲另一個時區

代碼:

 apiDate = "2013-04-16T16:05:50Z"; 
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); 
     Date date = dateFormat.parse(apiDate); 

     Calendar calendar = Calendar.getInstance(); 
     TimeZone timeZone = calendar.getTimeZone(); 

     SimpleDateFormat newDateFormat = new SimpleDateFormat("hh:mm aa, MMMM dd, yyyy"); 
     newDateFormat.setTimeZone(timeZone); 
     String newDateString = newDateFormat.format(date); 
+0

[將UTC日期轉換爲其他時區]可能的重複(http://stackoverflow.com/questions/6088778/converting-utc-dates-to-other-timezones) –

+0

是的,它實際上是重複的。對不起,我確實花了很長時間尋找答案,但我並沒有偶然發現。不管怎麼說,還是要謝謝你 ! –

+0

當您鍵入您的問題主題時,它會自動彈出,這也是爲什麼它也是此屏幕右側的頂部鏈接。 –

回答

2

你應該設置你的 「解析」 SimpleDateFormat爲UTC。否則,將實際假設缺省時區在分析時:

TimeZone utc = TimeZone.getTimeZone("Etc/UTC"); 
dateFormat.setTimeZone(utc); 

你也不需要構造一個日曆讓系統默認時區 - 只需使用:

TimeZone defaultZone = TimeZone.getDefault(); 
+0

太棒了,非常感謝。我知道有些東西不見了...... –

0
import java.util.Date; 
import java.util.TimeZone; 
import java.text.SimpleDateFormat; 

public class Test { 

    public static final SimpleDateFormat fDateTime = new SimpleDateFormat(
      "yyyy-MM-dd'T'HH:mm:ss"); 

    public static void main(String[] args) { 

     String output = getFormattedDate("2016-03-1611T23:27:58+05:30"); 
     System.out.println(output); 

    } 

    public static String getFormattedDate(String inputDate) { 

     try { 
      Date dateAfterParsing = fDateTime.parse(inputDate); 

      fDateTime.setTimeZone(TimeZone.getTimeZone("timeZone")); 

      return fDateTime.format(dateAfterParsing); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 
相關問題