2016-04-22 8 views
1

GMT時間を現地時間に変換する次のコードを持っています。私はここからStackOverflowで答えを取り出しました。問題はこのコードがGMT時間。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

私は、出力ではありません:それは、デバイスからのオフセットGMTを取るとして1970年1月1日14:00、私は、それは年に関係ないと思う、なぜそれ年も必要ですか? 。 – Jaeger

+0

ヨーロッパ/ロンドンのGMTオフセットがUnixエポック(1970/01/01)で実際に+ 1hだったのは分かりませんでした。その時、英国は1968年10月27日から1971年10月31日まで](https://en.wikipedia.org/wiki/British_Summer_Time#Periods_of_deviation)。 yyyy/01/01では、以来毎年+ 0hでした。このような理由から、年を知らなければ、正しく変換することはできません。 –

+0

さらに、夏時間は毎年同じ日に開始され、終了しません。 –

関連する問題