Reputation: 1065
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?
Upvotes: 2
Views: 3864
Reputation: 942
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.
Upvotes: 2
Reputation: 47280
I think you will first need to match the string pattern, then pass that matched substring to jodatime.
Upvotes: 1
Reputation: 89169
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.
Upvotes: 0
Reputation: 47183
Just use the relevant substring; 2009-05-15
and parse that with pattern yyyy-MM-dd
.
Upvotes: 3