SimpleDateFormat showing weird date after formatting – Solution


I recently had problems converting dates into format i want:

Problem : For example i was given some data with dates like “12 May 2012” which has a format of dd MMM yyyy and i wanted to change the format to dd-MM-yyyy, the Data was send from a US company and hence was formatted using US Locale. Now when i try to convert the said date to my needed format using SimpleDateFormat object it gives some other date or no date at all in some cases.

Solution : Well the solution to this problem is setting proper locale using Locale static strings as shown below:

SimpleDateFormat sdf = new SimpleDateFormat(“dd MMM yyyy”); //input format

sdf.setDateFormatSymbols(new DateFormatSymbols(Locale.US)); //set LOCALE

String str = “13 June 2012”;
Date date= sdf.parse(str); // get Date object

So we get the correct date by setting the proper Locale. After which we can format the date to any needed format.

Advertisements

About Dominic

J for JAVA more about me : http://about.me/dominicdsouza
This entry was posted in Thechy Stuff. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s