AppiDevo
AppiDevo

Reputation: 3225

Joda - DateTimeFormat - switching position of "MM" and "dd" depending on default Locale

I have LocalDate, and I want to print the date with day/month as 2 digit, full year and '-' as separator.

Of course I can use sth like this:

DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MM-yyyy");
dtf.print(localDate);

and it shows:

17-09-2012
18-09-2012
19-09-2012

But this is OK only for my Locale, what with the others? For example USA should be:

09-17-2012
09-18-2012
09-19-2012

How to do this?

There is

DateTimeFormatter dtf = DateTimeFormat.shortDate();

which switches position of day and month by itself. But it only prints:

(my locale):
17/9/12
18/9/12
19/9/12
(USA locale):
9/17/12
9/18/12
9/19/12

Upvotes: 1

Views: 3160

Answers (1)

Modus Tollens
Modus Tollens

Reputation: 5123

From the DateTimeFormatter API:

// print using the defaults (default locale, chronology/zone of the datetime)
String dateStr = formatter.print(dt);
// print using the French locale
String dateStr = formatter.withLocale(Locale.FRENCH).print(dt);
// print using the UTC zone
String dateStr = formatter.withZone(DateTimeZone.UTC).print(dt);

So, you can use a Locale or a DateTimeZone with you DateTimeFormatter.

However, since a pattern is set, the output will still be the same.

You could define your DateTimeFormatter using a style instead:

DateTimeFormatter dtf = DateTimeFormat.forStyle("M-");

and print it with the Locale.

Upvotes: 4

Related Questions