【问题标题】:android format datetime from django来自django的android格式日期时间
【发布时间】:2018-06-17 21:48:29
【问题描述】:

我正在使用 json 和其他框架将我的 django 网站连接到一个 android 应用程序

json 数据包含这样的日期时间:

{
   date: "2018-06-05T12:42:48.545140Z"
}

当 android 收到日期时,我尝试使用此代码对其进行格式化:

    String dt="2018-06-05T12:42:48.545140Z";
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm");
    String date=formatter.format(Date.parse(dt));

我收到以下错误:

java.lang.IllegalArgumentException:

解析错误:2018-06-14T14:30:02.982009Z

在 java.util.Date.parseError(Date.java:367)

在 java.util.Date.parse(Date.java:448)

在 django 模板中我可以轻松做到这一点

{{article.date|date:'d-m-Y H:i'}}

但在android中我有点困惑

【问题讨论】:

  • 过时的Date 类的parse 方法已弃用,请勿使用。整个班级也早已过时,而且从来没有精心设计过。考虑将 ThreeTenABP 添加到您的 Android 项目中,以便使用现代 Java 日期和时间 API java.time。使用起来感觉好多了。

标签: java android django date parsing


【解决方案1】:

如果您使用的是java.time API,您可以使用:

String dt = "2018-06-05T12:42:48.545140Z";
ZonedDateTime zdt = ZonedDateTime.parse(dt); 
String newFormat = zdt.format(DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm"));
System.out.println(newFormat);//05/06/2018 12:42

请注意,我不使用任何格式化程序,ZonedDateTime 的默认之一可以解析您的日期。

或者正如@Basil Bourque 所说,解析为Instance 而不是ZonedDateTime 更合适:

String newFormat = Instant.parse(dt)
        .atZone(ZoneId.of("Pacific/Auckland"))
        .format(DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm"));

关于您的错误

您的错误来自Date.parse(dt),因为 Date 的默认模式无法解析您的日期,您需要为其提供正确的格式,以便它了解如何格式化您的日期。例如:

String date = formatter.format(
        new SimpleDateFormat("the pattern which match your string date (dt)").format(dt)
);

但无论如何我不建议使用SimpleDateFormatDate

ThreeTen-Backport 项目以几乎相同的 API 语法将大部分 java.time 功能向后移植到 Java 6 和 7。进一步适用于ThreeTenABP 项目中的早期 Android (How to use ThreeTenABP

【讨论】:

  • 谢谢,但是 java.time api 需要 api 级别 26,我不想更改 min sdk,所以我更改了序列化程序类中的日期格式
  • @AmineMessaoudi 这可能对其他人有帮助,在任何情况下,您都可以使用类似的库 threeten.org/threetenbp/index.html,它提供 java.time 的功能
  • 很好的答案,但解析为 Instant 而不是 ZonedDateTime 会更合适。 Z 仅代表与 UTC 的偏移,而不是时区。
  • @YCF_L 是的,你是对的,Instant 是一个基本类,不用于生成自定义格式的字符串。对于自定义字符串,请使用 OffsetDateTimeZonedDateTime。但正如我所说,这里看到的带有Z 的输入是与UTC 的偏移量(偏移量为零),但不是 时区。时区是过去、现在和未来对特定区域的人们使用的偏移量的历史记录,名称为Continent/Region 格式。所以你将给定的输入解析为ZonedDateTime 是一种误导,尽管这在技术上是有效的。相反,解析为OffsetDateTime
  • 我上面的 cmets 假设意图是在 UTC 中感知日期和时间。相反,如果目标是调整到特定时区,则解析为Instant,应用ZoneId 以获得ZonedDateTime。像这样:Instant.parse( "2018-06-05T12:42:48.545140Z" ).atZone( ZoneId.of( "Pacific/Auckland" ) ).format( DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm") )
【解决方案2】:

我通过更改序列化程序类中的日期格式解决了这个问题

    date = serializers.DateTimeField(format="%m/%d/%Y %H:%M", required=False, read_only=True)

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 2022-11-23
    • 2015-12-17
    • 2011-11-02
    • 2016-05-12
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多