2016-04-22 105 views
1

我有以下代碼將GMT時間轉換爲本地時間,我把它從一個答案在這裏StackOverflow,問題是,此代碼返回GMT時間的錯誤值。格林威治標準時間錯誤的方式本地隱瞞(錯誤值)

我的GMT時間是:+3,但代碼是使用+2,它需要從我的設備的GMT時間,我猜,我的設備的時間是+3 GMT。

下面的代碼:

 String inputText = "12:00"; 
    SimpleDateFormat inputFormat = new SimpleDateFormat 
      ("kk:mm", Locale.US); 
    inputFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 

    SimpleDateFormat outputFormat = 
      new SimpleDateFormat("kk:mm"); 
    // Adjust locale and zone appropriately 
    Date date = null; 
    try { 
     date = inputFormat.parse(inputText); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    String outputText = outputFormat.format(date); 
    Log.i("Time","Time Is: " + outputText); 

日誌回報:14:00

回答

4

本上,您正在做的轉換相關的日期。

您只指定小時和分鐘,因此計算是在1970年1月1日完成的。在那個日期,大概是您的時區的GMT偏移量只有2小時。

也指定日期。


SimpleDateFormat inputFormat = 
    new SimpleDateFormat("kk:mm", Locale.US); 
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 

SimpleDateFormat outputFormat = 
    new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US); 
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 

Date date = inputFormat.parse("12:00"); 

System.out.println("Time Is: " + outputFormat.format(date)); 

Ideone demo

輸出:

Time Is: 1970/01/01 12:00 

附加代碼來顯示夏令時/夏時制的影響:

SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US); 
gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 

SimpleDateFormat finlandFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US); 
finlandFormat.setTimeZone(TimeZone.getTimeZone("Europe/Helsinki")); 

SimpleDateFormat plus3Format = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US); 
plus3Format.setTimeZone(TimeZone.getTimeZone("GMT+3")); 

Date date = gmtFormat.parse("1970/01/01 12:00"); 
System.out.println("Time Is: " + gmtFormat.format(date)); 
System.out.println("Time Is: " + finlandFormat.format(date)); 
System.out.println("Time Is: " + plus3Format.format(date)); 

date = gmtFormat.parse("2016/04/22 12:00"); 
System.out.println("Time Is: " + gmtFormat.format(date)); 
System.out.println("Time Is: " + finlandFormat.format(date)); 
System.out.println("Time Is: " + plus3Format.format(date)); 

輸出:

Time Is: 1970/01/01 12:00 
Time Is: 1970/01/01 14:00 EET   <-- Eastern European Time 
Time Is: 1970/01/01 15:00 GMT+03:00 
Time Is: 2016/04/22 12:00 
Time Is: 2016/04/22 15:00 EEST  <-- Eastern European Summer Time 
Time Is: 2016/04/22 15:00 GMT+03:00 
+0

不是我,輸出爲:1970/01/01 14:00,我不認爲這是關係到一年,因爲它需要的GMT從設備偏移,那麼,爲什麼它還需要年嗎? 。 – Jaeger

+0

我敢打賭,你不知道在Unix時代(1970/01/01),歐洲/倫敦的GMT抵消時間實際上是1小時,因爲那個時候英國在1968年10月27日到1971年10月31日之間是永久夏令時](https://en.wikipedia.org/wiki/British_Summer_Time#Periods_of_deviation)。在yyyy/01/01之後,每年都是+ 0h。不知道這一年,你不能正確地轉換,因爲這樣的原因。 –

+0

另外,夏令時不會在每年的同一天開始和結束。 –

相關問題