如何强制Joda-Time仅解析String的一部分? [英] How to force Joda-Time to parse only part of String?
问题描述
假设我有以下日期(以字符串形式):
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
yyyy-MM-dd
我尝试使用 Joda-Time 来解析它:
DateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
format.withZone(zone).parseDateTime(string).toLocalDate();
我得到以下异常:
java.lang.IllegalArgumentException: Invalid format: "2009-05-15T23:00:00.000Z" is malformed at "T23:00:00.000Z"
有没有一种方法可以迫使Joda-Time忽略字符串的其余部分?
Is there a way how to force Joda-Time to ignore rest of the string?
推荐答案
我遇到了同样的问题,即多个日期格式,我只想忽略某一点之后的所有内容.我所做的是创建一个消耗所有DateTimeParser的对象,然后使用DateTimeFormatterBuilder将其添加.
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();
我希望能帮上忙.
这篇关于如何强制Joda-Time仅解析String的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!