Friday, January 8, 2016

Android ISO8601: How to Convert a Date to call APIs

I have needed to get a date in java converted to ISO8601 on android for awhile and struggled through a few different issues on my way to a working solution.

Since it's an app that I'm asking people to download, I don't like to increase the download size by even a few MBs. So even though Joda Time is great, I need a different way. In researching, I had to piecemeal a solution from various blogs and stackoverflow posts.

If you've ever been wondering,
- Does android have a standard way to convert to iso8601 format?
- Why isn't it easier to get a UTC date that follows iso8601 so I can just call the APIs?
Then hopefully I can save you some time.

Android ISO8601: UTC SimpleDateFormat


The following is a straightforward way to get a UTC ISO8601 string of a date object without using any external libraries.

SimpleDateFormat ISO8601DATETIMEFORMAT = new SimpleDateFormat("yyyy/MM/dd 'T'HH:mmZ");
TimeZone tz = TimeZone.getTimeZone("UTC");
ISO8601DATETIMEFORMAT.setTimeZone(tz);
String isoDate = ISO8601DATETIMEFORMAT.format( dtobject);

Android ISO8601: APIs Don't like Arabic Chars


But wait, sometimes this still sends over Arabic characters like:
\u0662\u0660\u0661\u0666-\u0660\u0662-\u0662\u0665T\u0660\u0664:\u0665\u0661Z 

We don't want that.  The solution turns out to be fairly simple.  Make sure that the SimpleDateFormat is always converting using the English language locale.

SimpleDateFormat ISO8601DATETIMEFORMAT = new SimpleDateFormat("yyyy/MM/dd 'T'HH:mmZ",Locale.ENGLISH);

**Credit goes to this StackOverflow Comment Suggesting Locale.English

Android ISO8601: A Convenience Class


To wrap it all up, here's a convenience method.  It can be dropped in without adding any major overhead to your app in terms of size or performance.

public class AndroidISO8601Util{


static SimpleDateFormat ISO8601DATETIMEFORMAT = new SimpleDateFormat("yyyy/MM/dd 'T'HH:mmZ",Local.ENGLISH);

//Note: this method is not thread safe because SimpleDateFormat is not thread safe
public static String getISO8601forAPI( Date dt){
TimeZone tz = TimeZone.getTimeZone("UTC");
ISO8601DATETIMEFORMAT.setTimeZone(tz);
return ISO8601DATETIMEFORMAT.format( dtobject);
}
}

1 comment:

  1. Casino de Monte-Carlo - The Casino de Monte-Carlo
    Casino de 화성 출장마사지 Monte-Carlo 전라남도 출장안마 in Monte-Carlo offers a variety 파주 출장샵 of gaming options with a huge selection of slots, table games and live games available. We 출장샵 have created a 안성 출장안마

    ReplyDelete