Joda Time

时间:2015-10-16 10:27:18

标签: java jodatime

我正在尝试以本地格式显示日期但没有年份。所以应该是:

  • 6月12日 for UK
  • 6月12日美国

有可能用Joda时间来实现吗?

我们尝试过“dd MMMM”模式,但它不起作用。 我们尝试StringFormat.longDate()并删除年份信息,但是有更优雅的解决方案吗?

1 个答案:

答案 0 :(得分:1)

在封面下,JodaTime使用JDK的java.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));
}

打印

October 20, 2015
20 October 2015

但是,模式仅针对四种样式预定义:短,中,长和完整,分别适用于日期和时间部分。请参阅DateTimeFormat#patternForStyle的JavaDoc:

  

第一个字符是日期样式,第二个字符是时间样式。为短格式指定'S'字符,为中等指定'M',为长指定'L',为完整指定'F'。通过指定样式字符' - '可以省略日期或时间。

因此,如果您想删除年份部分,则需要对从DateTimeFormat.patternForStyle()获得的模式进行后处理。这可以做到例如。通过删除所有“Y”和“y”字符,但一般来说,如果你想为任意语言环境做这件事,可以产生一些混乱的模式。

相关问题