Formatting a date the portable way

With this post I introduce a new category: Short Notes. I’ll create short posts about interesting parts of Java or recurring problems.

The start will be a post about formatting and parsing a Date. This seems an easy task.

Lets start and format a Date:

Date date;
... // Create a date
String formatted = DateFormat.getInstance().format(date);

If I now output the created String then it can result in

8/31/15 12:30 PM

In this case the Locale of the computer was en_US.

If I set my computer to Locale de_DE then the result is

31.08.15 12:30

That’s fine as long as you only present this to a user. If you want to parse this afterwards then you can get into trouble.

If you use this code for parsing

Date date = DateFormat.getInstance().parse(formatted);

then you will get a ParseException when the parsing and the formatting with different locales.

This is important to consider when transferring data between different computer.

Also consider e.g. writing log files. The log files will look different when created on computers with different Locale settings.

To avoid such problems simple define your formats explicitly, e.g.

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

 

Leave a Reply

Your email address will not be published. Required fields are marked *