问题
I'm trying to achieve showing date in local format but without year. So should be:
- 12 June for UK
- June 12 for US
Is it possible to achieve with Joda time?
We've tried "dd MMMM" pattern but it doesn't work.
We've tried StringFormat.longDate()
and strip year info but are there more elegant solution?
回答1:
Underneath the covers, JodaTime uses the JDK's java.text.DateFormat.getDateInstance(int style, Locale aLocale)
- see the sources of org.joda.time.format.DateTimeFormat.StyleFormatter#getPattern(Locale locale)
how it delegates to java.text.DateFormat
:
String getPattern(Locale locale) {
DateFormat f = null;
switch (iType) {
case DATE:
f = DateFormat.getDateInstance(iDateStyle, locale);
break;
case TIME:
f = DateFormat.getTimeInstance(iTimeStyle, locale);
break;
case DATETIME:
f = DateFormat.getDateTimeInstance(iDateStyle, iTimeStyle, locale);
break;
}
if (f instanceof SimpleDateFormat == false) {
throw new IllegalArgumentException("No datetime pattern for locale: " + locale);
}
return ((SimpleDateFormat) f).toPattern();
}
so the per-locale formats are embedded in the JDK, not even in JodaTime.
Using this code, you can get the predefined patterns and outputs for different locales:
public static void main(String[] args) {
DateTime dt = DateTime.now();
String usFormat = DateTimeFormat.patternForStyle("L-", Locale.US);
String ukFormat = DateTimeFormat.patternForStyle("L-", Locale.UK);
System.out.println(dt.toString(usFormat));
System.out.println(dt.toString(ukFormat));
}
prints
October 20, 2015
20 October 2015
However, the patterns are predefined for four styles only: short, medium, long and full, applicable for both date and time parts separately. See the JavaDoc of DateTimeFormat#patternForStyle:
The first character is the date style, and the second character is the time style. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-'.
So if you want to drop the year part, you would need to post-process the pattern obtained from DateTimeFormat.patternForStyle()
. This could be done eg. by dropping all "Y" and "y" characters, but in general, if you want to do it for an arbitrary locale, can produce some messed-up patterns.
来源:https://stackoverflow.com/questions/33168198/localised-date-format-without-year-with-joda-time