Work-around for a Joda Time bug in PeriodFormat?

二次信任 提交于 2019-12-23 17:06:44

问题


Here's my code which reveals a Joda Time bug:

import org.joda.time.Period;
import org.joda.time.format.PeriodFormat;
import org.joda.time.format.PeriodFormatter;

import java.util.Locale;

public class ScratchSpace {

    public static void main(String[] args) {
        Locale.setDefault(Locale.GERMAN);
        final PeriodFormatter periodFormatter = 
                 PeriodFormat.wordBased(Locale.ENGLISH);
        final Period period = new Period(6, 5, 4, 3);
        final String s = period.toString(periodFormatter);
        // i'm expecting english to be outputted
        System.out.println("s = " + s); // outputs german: 6 Stunden, 5 Minuten, 4 Sekunden und 3 Millisekunden
    }

}

According to the JavaDocs I should be getting the period formatted in English. But it is using the current default locale instead, which in the example above is German.

I'm using Joda Time 2.0, on Mac OS X 10.7, with the computer set to "Australian English" as the preferred language.

Any simple work-around you can suggest?


回答1:


Okay, I've found a work-around:

final PeriodFormatter periodFormatter = 
             PeriodFormat.wordBased(new Locale(""));

However there is clearly a bug present in PeriodFormat. For example, the JavaDocs for PeriodFormat.getDefault() says:

Gets the default formatter that outputs words in English.
 This calls {@link #wordBased(Locale)} using a locale of {@code ENGLISH}.

whereas the result for me is that the user's current locale is used instead when I execute this:

final PeriodFormatter periodFormatter = PeriodFormat.getDefault();



回答2:


Another solution is to update to the latest Joda Time source...according to this bug report it is now fixed: http://sourceforge.net/tracker/?func=detail&aid=3471414&group_id=97367&atid=617889



来源:https://stackoverflow.com/questions/10106143/work-around-for-a-joda-time-bug-in-periodformat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!