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
<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
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("yyyy-MM-dd HH:mm");<br />