Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Android's date Strings to date objects

In Android, the date of every event (such as birthdays and anniversaries) is saved in String format, e.g. "2011-12-24".

This is at least the case for my phone. Some other phones may perhaps store these dates in other formats if they have a calendar different from the Gregorian one.

Even for phones with the Gregorian calendar set, there are date Strings with hours and minutes and without. I get such a date String when I query the contacts table for an event:

cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.ST‌​ART_DATE))

This results in (for example):

"2011-12-14" or "2011-12-24T00:00:00Z"

You can see that there are lots of different possible formats. In order to calculate with dates, I need to convert them from String to Date objects, needn't I?

How can I do this?

PS: I know there is a parse function for java date objects:

DateFormat myDateFormat = new SimpleDateFormat("dd/MM/yy");
Date tempDate = myDateFormat.parse("24/12/2011");

But in Android, I don't know which format I'll be confronted with, do I?

like image 752
caw Avatar asked Sep 19 '26 01:09

caw


1 Answers

Android works with date objects. Anytime you need to parse a date from string is because that date has been serialized, most likely in a file. In that case, you would know the format that was used. Date object is used in preferences, date object is used almost everywhere I can think of that relates to shared services, activites, etc. This means, there's almost never a need to parse string from date unless, like I said you're working with serialized source, reading it from a web service etc. If you can tell us your scenario, you might get more specific answer.

You can get the currently set date format like this:

DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
like image 130
Tomislav Markovski Avatar answered Sep 20 '26 13:09

Tomislav Markovski