The Unparseable Date Pitfall

Here is another pitfall with the SimpleDateFormat class.
Unlike my previous blog entry, this pitfall is not a multithreading issue; the following code is thread-safe. However, it can fail in certain situations.

package com.udojava.blog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ParseDateDemo {

	public static void main(String[] args) throws ParseException {
		String dateString = "Thu Oct 25 6:12 pm PDT 2012";

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"EEE MMM d h:mm a z yyyy");

		Date theDate = dateFormat.parse(dateString);

		System.out.println(dateFormat.format(theDate));
	}

}

The code will run on a lot of systems without ever failing, but on certain system setups, it will fail.

For example, on my computer it won’t run and instead produce the following exception:

Exception in thread "main" java.text.ParseException: Unparseable date: "Thu Oct 25 6:12 pm PST 2012"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.udojava.blog.ParseDateDemo.main(ParseDateDemo.java:15)

This is simply because my system is set up with a German locale setting, which does not understand the English names for the day (Thu) and month (Oct). The code will fail on all systems, which do not run under an English locale setup.

You can test it, by giving the Java arguments –Duser.country=DE –Duser.language=de when starting the program. This will set the Java default locale to German/Germany.

Now how to fix it? Starting the program with –Duser.language=en and forcing the users to use your locale is certainly not a good way to go.

Luckily, we can take care that the SimpleDateFormat class works with the correct locale, simply by adding a locale parameter to the constructor:

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"EEE MMM d h:mm a z yyyy", Locale.ENGLISH);

Now the program will run correctly, no matter what default locale Java is using.

The “write once, run anywhere” slogan from Java needs most of the time more care by the programmer than just using the Java programming language.

Advertisements

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

%d bloggers like this: