【问题标题】:Android convert gmt time to readable dateAndroid将gmt时间转换为可读日期
【发布时间】:2026-02-08 10:40:01
【问题描述】:

在 android 中,我想将“2015-11-10T17:00:00-0500”转换为可读的日期格式,例如:

2015 年 11 月 31 日
2015 年 11 月 31 日下午 4:00:00
下午 4:00:00 中午 12:00:00

最好的方法是什么,我已经尝试过使用 Date 方法但失败了

【问题讨论】:

  • 向我们展示您当时的尝试和失败。 (注意DateFormat 应该在某处涉及......

标签: java android datetime gmt


【解决方案1】:

只需使用 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) {
}

【讨论】:

    【解决方案2】:

    java.time

    旧的日期时间 API(java.util 日期时间类型及其格式类型 SimpleDateFormat)已过时且容易出错。建议完全停止使用,改用java.timemodern date-time API*

    您的日期时间字符串的时区偏移量为-0500,即UTC中的相应日期时间为2015-11-10T22:00:00Z,其中Z代表祖鲁语,timezone designator代表零时区偏移量,即Etc/UTC timezone 的时区偏移量为+00:00 hours。

    表示日期时间和时区偏移的类型是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 了解有关 modern date-time API* 的更多信息。


    * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

    【讨论】:

      最近更新 更多