2015-07-21 108 views
0

在我的android應用程序中,我必須解析格式爲EEE, dd MMM yyyy HH:mm:ss zzz的日期。我正在使用下面的方法從中提取時間。這工作完美。但時間總是以GMT格式顯示,所以我必須將其轉換爲用戶時區,因爲在解析之前我已在代碼中添加了一行,代碼爲inputFormatter.setTimeZone(TimeZone.getDefault()); ,因爲這不起作用我已更改參數在TimeZone.getTimeZone("UTC"),TimeZone.getTimeZone("Asia/Kolkata")等等,但沒有任何作品,時間仍然以格式。將GMT時區轉換爲用戶特定時區

這實際上是什麼問題?我怎麼能解決這個問題,任何幫助表示讚賞

public static String extractTime(String dateInput) { 
     Date date = null; 
     String time; 

     try { 
      DateFormat inputFormatter = new SimpleDateFormat(mFormat, Locale.getDefault()); 
      date = inputFormatter.parse(dateInput); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
     SimpleDateFormat outputFormatter = new SimpleDateFormat("HH:mm:ss"); 
     time = outputFormatter.format(date); 
     return time; 
    } 

更新

我已經嘗試設置時區以outputFormatter而不是inputFormatter,但它仍然是相同的,在輸出沒有變化。

例子:

輸入:Tue, 21 Jul 2015 09:02:30 GMT

輸出獲得:05:02:30

+0

您應該將timeZone設置爲'outputFormatter'而不是'inputFormatter'。 – Codebender

+0

讓我試試 – droidev

+0

@Codebender沒有改變它是一樣的 – droidev

回答

1

幾件事情需要注意的日期,日期格式。 Java中的日期對象始終採用UTC - 打印方式(即使在System.out.println()等事件中)取決於時區(例如,在sysout中,timeZone是系統的默認TZ)。

所以,說了讓我們來解決您的問題。您首先要解析包含某個時間區域中的日期的字符串。讓我們假設datestring是在用戶的TZ - 將其轉換爲正確的UTC時間,你必須告訴其TZ字符串在它解析日期格式:

// Assuming you have the userTimeZone already 
inputFormatter.setTimeZone(userTimeZone); 

現在當你分析你的日期正確的java.util.Date對象。如果你想格式化這個來獲得一個只包含小時,分鐘和秒的字符串,你就必須定義所需的目標TZ。假設這也是用戶的TZ:

outputFormatter.setTimeZone(userTimeZone); 

現在當你格式化這個格式,你會得到用戶的TZ時間字符串的日期。

相關問題