...
The concepts of days and years are universal, but the way in which dates are represented varies across cultures and are therefore specific to locales. This noncompliant code example examines the current date and prints one of two messages, depending on whether or not the month is June.:
Code Block | ||||
---|---|---|---|---|
| ||||
import java.util.Date; import java.text.DateFormat; import java.util.Locale; // ... public static void isJune(Date date) { String myString = DateFormat.getDateInstance().format(date); System.out.println("The date is " + myString); if (myString.startsWith("Jun ")) { System.out.println("Enjoy June!"); } else { System.out.println("It's not June."); } } |
...
but fails on other locales. For example, the output for a German locale (specified by -Duser.language=de
) is:
Code Block |
---|
The date is 20.06.2014 It's not June. |
...
This compliant solution forces the date to be printed in an English format, regardless of the current locale.:
Code Block | ||||
---|---|---|---|---|
| ||||
String myString = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US).format(rightNow.getTime()); /* Rest of code unchanged */ |
...