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:

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

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

<br />
8/31/15 12:30 PM<br />

In this case the Locale of the computer was en_US.

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

<br />
31.08.15 12:30<br />

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

<br />
Date date = DateFormat.getInstance().parse(formatted);<br />

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.

<br />
DateFormat df = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm&quot;);<br />

 

Leave a Reply

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