2

let's assume I have following dates (in String):

2009-05-15T23:00:00
2009-05-15T23:00:00.000Z 
2009-05-15

I don't care about the time and zone, only date is relevant for me. So I want to try to parse it with following pattern:

yyyy-MM-dd

I try to parse it using Joda-Time:

DateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
format.withZone(zone).parseDateTime(string).toLocalDate();

and I get following exception:

java.lang.IllegalArgumentException: Invalid format: "2009-05-15T23:00:00.000Z" is malformed at "T23:00:00.000Z"

Is there a way how to force Joda-Time to ignore rest of the string?

4 Answers 4

3

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

2
  • Thanks - the point is, that i have lots of formats that might differ in the last part...
    – krtek
    Nov 11, 2010 at 10:59
  • @krtek: well, a substring(0, 10) would match 2009-05-15 in all of cases you mentioned ;-)
    – darioo
    Nov 11, 2010 at 12:11
2

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.

1

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

0

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.

1
  • Date format can be very different as they come from different sources - please see reformatted question.
    – krtek
    Nov 11, 2010 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.