Java – Android format datetime from Django

Android format datetime from Django… here is a solution to the problem.

Android format datetime from Django

I’m using JSON and other frameworks to connect my Django website to an Android app

JSON data contains datetimes like this:

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

When android receives the date, I try formatting it with the following code:

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

I get the following error:

java.lang.IllegalArgumentException:

Parsing error: 2018-06-14T14:30:02.982009Z

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

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

I can easily do this in a django template

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

But in android I’m a little confused

Solution

If you use java.time APIs you can use:

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

Note that I don’t use any formatters, the default ZonedDateTime can parse your date.

or as @Basil Bourque It is more appropriate to mention that it is more appropriate to resolve it to Instance instead of ZonedDateTime:

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

About your mistake

Your error comes from Date.parse(dt) because the default mode of Date cannot parse your date, you need to provide it with the correct format so that it can understand how to format your date. For example:

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

But I wouldn’t recommend using SimpleDateFormat or Date anyway.

the ThreeTen-Backport project was backported to most of Java 6 and 7 java.time has almost the same API syntax. Further in <a href=”https://github.com/JakeWharton/ThreeTenABP” rel=”noreferrer noopener nofollow” > ThreeTenABP for earlier Android (<26) projects. See also How to use ThreeTenABP

Related Problems and Solutions