I have a LocalDate and I would like to print the date with day and month as 2 digit and the year as 4 digit, based on Locale format pattern. Actually, I can use the DateTimeFormatter to set the short date, but unfortunately "I can't" change the default pattern...Is there a method to do this?
Below, I explain this with an example:
Locale l = Locale.ITALIAN;
LocalDate localDate = new LocalDate( 2014, 8, 28);
DateTimeFormatter formatterOutput1 = DateTimeFormat.shortDate().withLocale(l);
System.out.println( "Output1: " + formatterOutput1.print(localDate));
l = Locale.ENGLISH;
DateTimeFormatter formatterOutput2 = DateTimeFormat.shortDate().withLocale(l);
System.out.println( "Output2: " + formatterOutput2.print(localDate));
This is the result:
Output1: 28/08/14
Output2: 8/28/14
So, the output is correct, but I expect this:
Output1: 28/08/2014
Output2: 08/28/2014
How can I change the default pattern?
Thanks!
Instead of using shortDate()
a way to do it is by using forStyle()
using the S
for Date and -
for Time
DateTimeFormat.patternForStyle("S-", Locale.ITALIAN);
Then do a String replace on the Pattern to change your yy
into yyyy
Example:
LocalDate localDate = new LocalDate(2014, 8, 28);
String pattern = DateTimeFormat.patternForStyle("S-", Locale.ITALIAN);
pattern = pattern.replace("yy", "yyyy");
DateTimeFormatter formatterOutput1 = DateTimeFormat.forPattern(pattern);
System.out.println("Output1: " + formatterOutput1.print(localDate));
Which will print:
Output1: 28/08/2014
Same goes with ENGLISH Locale:
String patternEnglish = DateTimeFormat.patternForStyle("S-", Locale.ENGLISH);
patternEnglish = patternEnglish.replace("yy", "yyyy");
DateTimeFormatter formatterOutput2 = DateTimeFormat.forPattern(patternEnglish);
System.out.println("Output2: " + formatterOutput2.print(localDate));
Which will print:
Output2: 8/28/2014
Note that with this approach you don't have to worry about knowing all Locale formats if you only care about making the YEAR part 4 digits.
You should compose your own format pattern. In your particular case it will be:
DateTimeFormatter formatterOutput1 = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTimeFormatter formatterOutput2 = DateTimeFormat.forPattern("MM/dd/yyyy");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With