How to force Joda-Time to parse only part of String?

青春壹個敷衍的年華 提交于 2019-12-06 10:08:11
etherton

I had the same problem, multiple date formats where I just wanted to ignore everything after a certain point. What I did was create a consume all DateTimeParser and then add that using a DateTimeFormatterBuilder.

I believe this would meet your needs:

JodaDateTimeConsumeAll.java:

public class JodaDateTimeConsumeAll implements DateTimeParser{

    @Override
    public int estimateParsedLength() {
        return 100;
    }

    @Override
    public int parseInto(DateTimeParserBucket bucket, String text, int position) {
        return text.length(); //consume the whole thing
    }

}

FormatterBuilder:

DateTimeParser dtp = new DateTimeFormatterBuilder()
    .appendYear(4,4)
    .appendLiteral("-")
    .appendDayOfMonth(2)
    .appendLiteral("-")
    .appendMonthOfYear(2)
    .append(new JodaDateTimeConsumeAll())
    .toFormatter()
    .getParser();

I hope that helps.

Just use the relevant substring; 2009-05-15 and parse that with pattern yyyy-MM-dd.

I think you will first need to match the string pattern, then pass that matched substring to jodatime.

You can always ignore the Timezone after the date has successfully been parsed.

For now use the pattern (for your date string format 2009-05-15T23:00:00.000Z)

yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Are your date format the same throughout your application or are they different?


Based on your edited post, it seems you don't really need the time part, so just get the relevant first 10 characters of the date string and parse it with yyyy-MM-dd format.

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