[英]Android convert gmt time to readable date
在android中,我想將“2015-11-10T17:00:00-0500”轉換為可讀的日期格式,例如:
2015 年 11 月 31 日
2015 年 11 月 31 日下午 4:00:00
下午 4:00:00 中午 12:00:00
最好的方法是什么,我已經嘗試過使用 Date 方法但失敗了
只需使用SimpleDateFormat,如下所示:
String time = "2015-11-10T17:00:00";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("hh:mm:ss dd.MM.yyyy");
try {
Date date = dateFormat.parse(time);
String out = dateFormat2.format(date);
Log.e("Time", out);
} catch (ParseException e) {
}
遺留日期時間 API( java.util
日期時間類型及其格式類型SimpleDateFormat
)已過時且容易出錯。 建議完全停止使用它並切換到java.time
, 現代日期時間 API * 。
您的日期時間字符串的時區偏移量為-0500
即 UTC 中的相應日期時間為2015-11-10T22:00:00Z
,其中Z
代表祖魯語,是零時區偏移的時區指示符,即Etc/UTC
時區它的時區偏移為+00:00
小時。
表示日期時間和時區偏移的類型是OffsetDateTime
。 為了將其格式化為不同的模式,您需要一個DateTimeFormatter
。
演示:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d'T'H:m:sXX", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("2015-11-10T17:00:00-0500", dtfInput);
DateTimeFormatter dtfOutput1 = DateTimeFormatter.ofPattern("EEE dd, uuuu", Locale.ENGLISH);
DateTimeFormatter dtfOutput2 = DateTimeFormatter.ofPattern("EEE dd, uuuu h:mm:ss a", Locale.ENGLISH);
DateTimeFormatter dtfOutput3 = DateTimeFormatter.ofPattern("h:mm:ss a", Locale.ENGLISH);
String output1 = dtfOutput1.format(odt);
String output2 = dtfOutput2.format(odt);
String output3 = dtfOutput3.format(odt);
System.out.println(output1);
System.out.println(output2);
System.out.println(output3);
}
}
輸出:
Tue 10, 2015
Tue 10, 2015 5:00:00 PM
5:00:00 PM
從Trail: Date Time 中了解有關現代日期時間 API * 的更多信息。
* 出於任何原因,如果您必須堅持使用 Java 6 或 Java 7,您可以使用ThreeTen-Backport,它將大部分java.time功能向后移植到 Java 6 和 7。如果您正在為 Android 項目和您的 Android API 工作級別仍然不符合 Java-8,請檢查 通過 desugaring和How to use ThreeTenABP in Android Project 可用的 Java 8+ APIs 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.