Joda Time bug or my mistake? (Java Joda Time dates as strings parsing)

后端 未结 3 489

so I was having a problem parsing a date, using the JodaTime chronology IslamicChronology so wrote a small example to demonstrate my problem.

Here\'s th

3条回答
  •  爱一瞬间的悲伤
    2020-12-12 01:54

    If anyone's interested...I've found a work around:

    • Create a new class e.g. IslamicChronologyWithNames which delegates to an instance of IslamicChronology in package org.joda.time.DateTimeZone
    • Modify the one method; assemble(Fields fields): call the delegate's method and then set fields.monthOfYear (and possibly dayOfWeek) to you own subclass of BasicMonthOfYearDateTimeField
    • The subclass of BasicMonthOfYearDateTimeField can then lookup in property files names for the month's (or day's if DayOfWeek...) name. Subclass needs to be in package org.joda.time.chrono to be able to extend BasicMonthOfYearDateTimeField.

    There is still an issue that Joda time seems to validate the date you are parsing before calling methods of subclass like getAsText(int fieldValue, Locale locale) and because it has no knowledge of the month names that your class returns, fails validation and so never calls the methods. My work-around was to have a static method in this class which converts a date as a string with islamic month names into a date as a string with gregorian english month names. So before calling parseDateTime(), call the static method and then the date string passes validation. Then, instead of processing Islamic month names in the convertText() method, use the default gregorian implementation inside your subclass:

    protected int convertText(String text, Locale locale)
    {
        return GJLocaleSymbols.forLocale(locale).monthOfYearTextToValue(text);
    }
    

    That should work! Hope it makes sense for anyone who has the same problem.

提交回复
热议问题