4

For my Android app I'm using Joda Time to print localized Date, as follows:

String date = DateTimeFormat.shortDate().print(new LocalDate());

But this gives me a two-digit year.

So, how can I do to display the year as a four-digit number regardless of the current user Locale? And, how can I append a 0 before day or month if they are < 10, again, regardless of the current user Locale?

durron597
  • 31,968
  • 17
  • 99
  • 158
Ernestina Juan
  • 957
  • 1
  • 9
  • 24
  • I'd guess don't use `shortDate()` but rather provide your own date format or use another provided format that does what you want. – Thomas Aug 12 '15 at 12:58
  • which version of Joda are you using? I do not see any method `shortDate()` method in `DateTime` – Nitesh Virani Aug 12 '15 at 12:59
  • Is it `DateTimeFormat`? – Thomas Aug 12 '15 at 13:00
  • It sounds like you don't actually want to use the locale settings, if you want to force yyyy, MM and dd rather than yy, M and d. If you're not going to make it an idiomatic local representation, why not just go the whole hog and specify the pattern fully? – Jon Skeet Aug 12 '15 at 13:00

2 Answers2

0

you can use below code snippet, it will give you the date in your format:

DateTimeFormat.forPattern("MM/dd/yyyy").print(new LocalDate())
Nitesh Virani
  • 1,688
  • 4
  • 25
  • 41
0

You're going to have create your own mapping.

Here's what already exists: Joda Time has a method DateTimeFormat.patternForStyle, which delegates to the patterns specified by the JDK in java.text.DateFormat. See Using Predefined Formats, which provides the following table:

Style       U.S. Locale             French Locale
DEFAULT     Jun 30, 2009            30 juin 2009
SHORT       6/30/09                 30/06/09
MEDIUM      Jun 30, 2009            30 juin 2009
LONG        June 30, 2009           30 juin 2009
FULL        Tuesday, June 30, 2009  mardi 30 juin 2009

You specify which Locale specific format you in patternForStyle by using S, M, L, F, and - to leave it blank. So, in your case, it sounds like you want date only, so use:

DateTimeFormat.patternForStyle("S-", locale);

Unfortunately, this option will result in a TWO digit year.

So, either do all of that, or **create your own map` of DateTimeFormatters for this purpose. Something like:

public class DateFormatterProvider {
  private final Map<Locale, DateTimeFormatter> formatterMap = new HashMap<>();

  public DateFormatterProvider() {
    formatterMap.put(Locale.US, DateTimeFormat.forPattern("dd/MM/yyyy"));
    formatterMap.put(Locale.FRENCH, DateTimeFormat.forPattern("MM/dd/yyyy"));
    // etc.
  }
}
durron597
  • 31,968
  • 17
  • 99
  • 158