String to Date Formatting Using Java (Android)

Have you been trying to find a quick and easy way to format dates from a String? It can be quite tricky with Java (if you're new to it). So, I'm going to go through a few very simple steps to accomplish just that.

Here's the full piece of code:


String dateStr = "04/05/2010";

SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
Date dateObj = curFormater.parse(dateStr);
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy");

String newDateStr = postFormater.format(dateObj);

And now I'll take you through the important pieces of the code step by step.


String dateStr = "04/05/2010";

This is just the string that's holding the date, which we are going to parse.


SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
Date dateObj = curFormater.parse(dateStr);

The first line instantiates a SimpleDateFormat object and tells it the format it should be looking for to parse. In this case it's dd/MM/yyyy which is identical to our date that we want to parse (04/05/2010).

The second line parses the date string and returns a Date object, which we'll be using later to format the date.


SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy");

String newDateStr = postFormater.format(dateObj);

And finally, we setup another SimpleDateFormat object for the new date format. We then call the format method and pass in the Date object that we created earlier. This returns a string with the newly created date format (ie. May 04, 2010).

Nice and user friendly!

jon | May 04, 2010 | Comments (3)

Comments

Awesome. Thank you.
The only one I could find in the web in this subject. Clear, clean and actually works.
I hope Google/Android would learn from you !
Comment by Ahmad - July 07, 2011 @ 9:29 pm
Thanks, this was pretty handy.
Comment by Johan - May 27, 2011 @ 4:21 pm
fantastic! why can't the official Android manual be so clear and easy to understand?
Comment by Dominik - May 12, 2011 @ 6:39 pm

Name (required)
Email (will not be published) (required)
Website

captcha