我有一個包含像這樣的日期字符串:如何在Android中轉換字符串日期格式?
String startTime = "2014-10-11T17:00:41+0000"
我想,這樣它讀取像這樣,而不是重新格式化字符串:
Oct 11, 2014 5:00 PM
我有一個包含像這樣的日期字符串:如何在Android中轉換字符串日期格式?
String startTime = "2014-10-11T17:00:41+0000"
我想,這樣它讀取像這樣,而不是重新格式化字符串:
Oct 11, 2014 5:00 PM
由於Date
對象不保存時區信息,因此需要專門設置原始日期的時區偏移量到目標格式化程序。下面是在保持時區偏移的情況下從一種格式轉換爲另一種格式的完整代碼(您的情況爲+ 0000)。有關TimeZone
類here的更多信息,以及如何爲您的要求here建立適當的日期和時間模式字符串。
try {
DateFormat originalFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat(
"MMM dd, yyyy K:mm a", Locale.ENGLISH);
targetFormat.setTimeZone(TimeZone.getTimeZone("GMT+0000"));
Date date = originalFormat.parse("2014-10-11T17:00:41+0000");
String formattedDate = targetFormat.format(date);
System.out.println(formattedDate);
} catch (ParseException e) {
e.printStackTrace();
}
輸出:2014年10月11日下午5:00
使用的SimpleDateFormat的解析輸入字符串和代表在新的格式: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
例:
SimpleDateFormat sdfmtIn = new SimpleDateFormat("dd/MM/yy");
SimpleDateFormat sdfmtOut= new SimpleDateFormat("dd-MMM-yyyy");
java.util.Date date = sdfmtIn.parse(strInput);
String strOutput = sdfmtOut.format(date);
使用Java的格式化程序:http://docs.oracle.com/javase/7/docs/api/java/util/Formatter。至少html是一個選項。 String.format()可能能夠做你所需要的,但它不提供Formatter的效率(通過http://stackoverflow.com/questions/513600/should-i-use-javas-string-format-if -performance-is-important) – zgc7009 2014-10-01 20:56:49
我敢建議使用jodatime? – 2014-10-01 22:11:13