Many people use the Date class in Android, and it's really handy. But it's deprecated in later Java versions, and in Android as well. Given the fact that it was once the de facto standard, it's still widely used. So, why not use it? You can just use @SuppressWarnings("deprecated"), right?

Wrong.

The Android Date code does not work as it should in many cases. It can produce incorrect numbers which can lead to disaster. Worse, it does not function the same on all devices. Yowch.

So, use Calendar instead. It is much easier to use, and always--always--produces correct results. How do we use it?

Take a look at this SO question, which involved using a Date object to set up a DatePicker. The user was receiving "Jan 1 1900" every time, without fail, even using a custom hard-coded time. So, I had him switch to Calendar.

Here is the original code (edited a bit for variables):

long timestamp = ...; // In seconds
Date date = new Date();
date.setTime(timestamp * 1000L);
datePickerDateDue.init(date.getYear(), date.getMonth(), date.getDay(), null);

And here is the modified code:

long timestamp = ...; // In seconds
Calendar c = Calendar.getInstance();
c.setTimeInMillis(timestamp * 1000L);
datePickerDateDue.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), null);
// Calendar.DATE also works for Calendar.DAY_OF_MONTH, but it seems to cause more ambiguity, so I avoid it.

All in all, a simple transition of code for a lot of payoff.

Next Post Previous Post