在Java 8中按时间段分析ISO日期 [英] Parse ISO date by Period in Java 8
问题描述
我想用替换
。 JodaTime
Java 8 DateTime API
i want to replace JodaTime
by Java 8 DateTime API
.
我有 ISO-8601
期间描述= P2W5DT11H8M
在 JodaTime
中,我非常简单地通过执行以下代码来解析:
In JodaTime
i parse it very simply by executing the following code:
Period.parse(P2W5DT11H8M)
,并获得成功的期限
对象。
Period.parse("P2W5DT11H8M")
and i get the successful Period
object.
我可以在Java 8中执行相同操作吗?
Can i do the same in Java 8?
推荐答案
Java 8中的期间只有年/月/日组件。持续时间有小时/分/秒/分钟。看来你需要手动解析字符串。一个选项可能看起来像下面的代码(您需要添加输入验证等) - 可能会有更好的选择。
A Period in Java 8 only has year/month/day components. A Duration has hour/minute/second components. It seems that you will need to parse the string manually. One option could look like the code below (you need to add input validation etc.) - there may be better alternatives.
public static void main(String[] args) {
System.out.println(PeriodAndDuration.parse("P2W5DT11H8M"));
}
public static class PeriodAndDuration {
private final Period p;
private final Duration d;
public PeriodAndDuration(Period p, Duration d) {
this.p = p;
this.d = d;
}
public Period getPeriod() {
return p;
}
public Duration getDuration() {
return d;
}
public static PeriodAndDuration parse(String input) {
int periodStart = input.indexOf("P");
int timeStart = input.indexOf("T");
Period p = Period.parse(input.substring(periodStart, timeStart));
Duration d = Duration.parse("P" + input.substring(timeStart, input.length()));
return new PeriodAndDuration(p, d);
}
@Override
public String toString() {
return p.toString() + d.toString();
}
}
这篇关于在Java 8中按时间段分析ISO日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!