【问题标题】:Get current date time in the desired format以所需格式获取当前日期时间
【发布时间】:2015-06-07 12:00:09
【问题描述】:

我想按以下格式获取当前日期时间

格林威治标准时间 2014 年 8 月 20 日星期二 22:51:31

但我发现很难将其转换为格式说明符 例如 ddmmyy 那样 我的疑问是象征性地指定 Tue 就像如何象征性地指定 GMT 一样。

【问题讨论】:

    标签: android datetime datetime-format datetimeformatinfo


    【解决方案1】:

    考虑使用SimpleDateFormat

    编辑:

    看起来您可能需要格式字符串“E d MMM y H:m:s z”。

    SimpleDateFormat format = new SimpleDateFormat("E d MMM y H:m:s z", Locale.US); String date = format.format(new Date());

    【讨论】:

    • 要求的格式是 RFC 1123(见另一个答案),可能 GMT 是要求的一部分,至少 RFC 1123 支持很少的时区缩写。所以我期待Sun, 9 May 2021 14:46:59 GMT。相反,从您的代码中我得到了Sun 9 May 2021 16:47:0 CEST,根据 RFC 1123,CEST 不是受支持的时区缩写。此外,0 秒可能应该写为00,而不仅仅是0
    【解决方案2】:

    java.time

    我建议您使用modern date-time API*

    您想要的格式是开箱即用的DateTimeFormatter.RFC_1123_DATE_TIME

    演示:

    import java.time.ZoneOffset;
    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class Main {
        public static void main(String[] args) {
            String strDateTime = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.RFC_1123_DATE_TIME);
            System.out.println(strDateTime);
        }
    }
    

    输出:

    Sun, 9 May 2021 14:36:28 GMT
    

    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

    【讨论】:

    • 就这样。它也适用于OffsetDateTime
    猜你喜欢
    • 1970-01-01
    • 2013-08-17
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2011-12-06
    相关资源
    最近更新 更多