2016-07-20 84 views
0

在我的代碼中,我獲取當前時間並根據「UTC」時區對其進行格式化,並使用相同的時區對其進行解析,從而將其轉換爲日期。問題是,我得到的日期,「星期三07月20日13時04分51秒GMT + 05:00 2016」比 其格式化和解析如下對於給定的Locale,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" 

現在uptil這裏的東西做工精細的代碼,與時區GMT + 05的時間:00被轉換成標準UTC與GMT + 00:由0000中格式化的日期所示

Date setteledDate = dateFormat.parse(dateText); 

現在解析日期如上給出以下日期00。 「Wed Jul 20 13:04:51 GMT + 05:00 2016」。問題是這個日期再次在GMT + 5 和我得到當前日期格式化並解析它的整個目的丟失,因爲目的是根據「UTC」(GMT + 00:00)獲取當前日期。

請幫忙。

+0

哪些Java版本是ü使用? –

+0

我正在使用Java 7. –

+0

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

回答

0

用SimpleDateFormat格式將Z替換爲z。

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 

//更新

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

我只是舉兩個時區的例子 – iAndroid

+0

是的,它根據我設置的時區格式。一旦我已經格式化與timezone UTC currentDate我得到正確的日期字符串,但是當我解析它使用相同的simpleDateFormat對象將其轉換爲Date對象(具有新的時區)時,它返回我在一開始的日期與初始時區一致)。 –

相關問題