Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change date pattern from shortDate() format in JodaTime

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!

like image 271
user3449772 Avatar asked Aug 28 '14 14:08

user3449772


2 Answers

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.

like image 71
gtgaxiola Avatar answered Nov 14 '22 23:11

gtgaxiola


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");
like image 43
Andremoniy Avatar answered Nov 14 '22 21:11

Andremoniy