Date handling in Android development


SDK Version: 
M3

This unusual topic came around quite a few times in the last couple of days, first with our own rss parser, and today with android-xmlrpc.
In our rss parser, we wanted to have as much flexibility as possible, so we could use many types of localized rss pages, that have different date formats.

Here are a few examples, for different date formats:
20100715T1043:11Z
2010-07-15T10:43:11Z
20100715104311
2010. july 15.
2010-07-15 10:43:11

Here is the cheat sheet in the android docs for date syntax.
Today I started working on an xml reader, and I used the android-xmlrpc library. It was hard coded to work with only one kind of date format, luckily, the source code is also included, so it's possible to set up my own flavour of date format.
Here is a little snippet, from our rss date value parser. It works like this: first it tries our custom SimpleDateFormat, than it tries several DateFormats.

  1. //usually we use this format
  2. SimpleDateFormat mSimpleDateFormat=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
  3.  
  4. item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener() {
  5.    public void end(String body) {
  6.        try {//first try our own format
  7.            mRssItem.mPublicationDate = mSimpleDateFormat.parse(body);
  8.        } catch (ParseException e4) {//if it fails, try other formats
  9.            DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, Locale.ENGLISH);
  10.            try {
  11.                mRssItem.mPublicationDate = df.parse(body);
  12.            } catch (ParseException e) {
  13.                df = DateFormat.getDateInstance(DateFormat.LONG, Locale.ENGLISH);
  14.                try {
  15.                    mRssItem.mPublicationDate = df.parse(body);
  16.                } catch (ParseException e1) {
  17.                    df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH);
  18.                    try {
  19.                        mRssItem.mPublicationDate = df.parse(body);
  20.                    } catch (ParseException e2) {
  21.                        df = DateFormat.getDateInstance(DateFormat.SHORT,Locale.ENGLISH);
  22.                        try {
  23.                            mRssItem.mPublicationDate = df.parse(body);
  24.                        } catch (ParseException e3) {
  25.                           // TODO log input format error
  26.                        }
  27.                    }
  28.                }
  29.            }
  30.        }
  31.    }
  32. });