2016-07-20 8 views
0

私のコードでは、現在の時刻を取得し、それを "UTC"タイムゾーンに従ってフォーマットし、同じタイムゾーンを使用してそれを解析してDateに変換します。今、物事が正常に動作し、ここでuptil よりも、そのフォーマットされ、JavaのsimpleDateFormatは、指定されたロケールで日付を正しく解析しませんか?

Calendar calendar = Calendar.getInstance(); 
    Date currentDate = calendar.getTime(); 
    //gives time as "Wed Jul 20 13:04:51 GMT+05:00 2016" 

    dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"); 
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 

    String dateText = dateFormat.format(currentDate); 
    //This formats dates as following "Wed, 20 Jul 2016 08:04:51 +0000" 

次のコードのように解析:問題は、私は「00 2016年7月20日水曜日午後一時04分51秒GMT + 05」と日付を取得するということですタイムゾーンGMT + 05と時間:

Date setteledDate = dateFormat.parse(dateText); 

すぐ上記のように日付を解析次の日付を与えるフォーマットされた日付に0000で示す00:00 GMT + 00標準UTCに変換されます。 「水曜日7月20日13:04:51 GMT + 05:00 2016」問題は、この日付がGMT + 5 に再びあり、現在の日付の書式を取得している私の全目的が、「UTC」(GMT + 00:00)に基づいて現在の日付を取得するために解析されているためです。

助けてください。

+0

を更新しますか? –

+0

私はJava 7を使用しています。 –

+0

http://stackoverflow.com/questions/21939967/java-simpledateformat-interpret-parse-string-as-utc –

答えて

0

Zをzに置き換えるのは、SimpleDateFormat形式です。

Calendar calendar = Calendar.getInstance(); 
Date currentDate = calendar.getTime(); 

//gives time as "Wed Jul 20 13:04:51 GMT+05:00 2016" 

SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); 
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 

String dateText = dateFormat.format(currentDate); 
Log.e("date",dateText); 
//output Wed, 20 Jul 2016 09:01:20 UTC 

dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 
dateText = dateFormat.format(currentDate); 
Log.e("date",dateText); 
//output Wed, 20 Jul 2016 09:02:04 GMT+00:00 

//は、Javaのバージョンはuが使用している

SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); 
     TimeZone.setDefault(TimeZone.getTimeZone("UTC")); 
     try { 

      Date date = dateFormat.parse("Wed Jul 20 13:04:51 GMT+05:00 2016"); 
      Log.e("date",date.toString()); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
+0

なぜ時間帯を変更していますか? –

+0

私はちょうど2つのタイムゾーンの例を与えます – iAndroid

+0

はい私は設定したタイムゾーンに従ってフォーマットを行います。一度私はタイムゾーンUTCで私は正しい日付文字列を取得currentDateをフォーマットしたが、私はそれをDateオブジェクト(これは新しいタイムゾーンを持つ)に変換するために同じsimpleDateFormatオブジェクトを使用して解析すると、私は非常に開始(初期タイムゾーンを使用しています)。 –

関連する問題