2011-10-21 44 views
-3

我是android新手。 我有以下日期轉換爲這個時間戳(Wed Oct 12 14:17:42 GMT+05:30 2011如何在java中轉換日期

Thu, 27 May 2010 12:37:27 GMT 

這是我從通過標題服務器獲取的日期。我已將其轉換爲String對象。現在我必須將其轉換爲日期格式,如:Wed Oct 12 14:17:42 GMT+05:30 2011

請你能幫助我如何使用時間戳將它轉換爲(Wed Oct 12 14:17:42 GMT+05:30 2011)這種格式。

回答

4

看看DateFormatSimpleDateFormat其中提供parse()format()方法。 DateFormat提供了一堆標準格式,而SimpleDateFormat允許您提供自己的格式表達式。

實例爲您輸入的日期:

//note that you need the locale as well, since the weekdays and months are written in a specific language, English in that case 
SimpleDateFormat parseFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH); 
SimpleDateFormat writeFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); 
writeFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 

Date tDate = parseFormat.parse("Wed, 12 Oct 2011 14:17:42 GMT"); 

System.out.println(writeFormat.format(tDate)); //Wed Oct 12 14:17:42 GMT 2011 

編輯:如果你想要一個更可用的API,嘗試JodaTime