【问题标题】:Android time in iso 8601ISO 8601 中的 Android 时间
【发布时间】:2012-11-10 23:56:05
【问题描述】:

使用 android 和 joda 时间库 - 我正在尝试转换用户的时区以便稍后将其格式化为:例如 2012-11-12T21:45:00+02:00。

DateTimeZone zone = DateTimeZone.forID( TimeZone.getDefault().getID());

上面的代码失败了 - 任何人都知道我怎样才能获取“欧洲/伦敦”(Timezone.getID)并将其转换为偏移量,以便我可以将其放入 ISO 8601 格式?

【问题讨论】:

    标签: android timezone jodatime iso8601


    【解决方案1】:

    如果我正确理解了您的目标,您可以直接使用SimpleDateFormat 类。

    示例代码:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.UK);
    String formattedDate = sdf.format(new Date());
    

    您可以在SimpleDateFormat 中查看文档

    问候。

    【讨论】:

    • 您的评论中缺少年份,但这是我在上面的代码中使用的格式。
    【解决方案2】:

    API 级别 26 增加了对来自 Java 的许多时间和日期类的支持。所以这个解决方案现在也可以应用: https://stackoverflow.com/a/25618897/3316651

    // works with Instant
    Instant instant = Instant.now();
    System.out.println(instant.format(DateTimeFormatter.ISO_INSTANT));
    
    // works with ZonedDateTime 
    ZonedDateTime zdt = ZonedDateTime.now();
    System.out.println(zdt.format(DateTimeFormatter.ISO_INSTANT));
    
    // example output
    2014-09-02T08:05:23.653Z
    

    感谢 JodaStephen。

    Android 文档: https://developer.android.com/reference/java/time/format/DateTimeFormatter.html#ISO_INSTANT

    【讨论】:

    猜你喜欢
    • 2011-01-10
    • 2013-12-06
    • 2023-04-11
    • 2010-10-23
    • 2013-04-05
    • 2013-03-11
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多