在幕后,JodaTime 使用 JDKjava.text.DateFormat.getDateInstance(int style, Locale aLocale)
- 查看来源org.joda.time.format.DateTimeFormat.StyleFormatter#getPattern(Locale locale)
它如何委托给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();
}
因此,每个语言环境的格式都嵌入在 JDK 中,甚至没有嵌入在 JodaTime 中。
使用此代码,您可以获得不同区域设置的预定义模式和输出:
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
但是,这些模式仅预定义为四种样式:短、中、长和完整,分别适用于日期和时间部分。请参阅 JavaDocDateTimeFormat#patternForStyle http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html#patternForStyle(java.lang.String,%20java.util.Locale):
第一个字符是日期样式,第二个字符是时间样式。指定字符“S”表示短样式,“M”表示中样式,“L”表示长样式,“F”表示全样式。可以通过指定样式字符“-”来省略日期或时间。
因此,如果您想删除年份部分,则需要对从以下位置获得的模式进行后处理DateTimeFormat.patternForStyle()
。这可以例如完成。通过删除所有“Y”和“y”字符,但一般来说,如果您想针对任意区域设置执行此操作,可能会产生一些混乱的模式。