我正在使用 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中我有点困惑
最佳答案
如果您使用 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)
);
但无论如何我都不建议使用 SimpleDateFormat
或 Date
。
ThreeTen-Backport项目向后移植到 Java 6 和 7 的大部分 java.time具有几乎相同的 API 语法的功能。在 ThreeTenABP 中进一步适用于早期的 Android(<26)项目。参见 How to use ThreeTenABP .
关于java - 来自django的android格式日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50900725/