具有通配符字段的Java 8 ISO 8601间隔语法 [英] Java 8 ISO 8601 Interval syntax with wildcard field(s)
问题描述
我需要解析类似于ISO 8601语法的时间间隔表达式,只允许对字段使用通配符;并将开始和结束存储到两个LocalDateTime
对象中.然后,我的Interval
将具有与第三个LocalDateTime
或OffsetDateTime
进行比较的API,以检查其是否在时间间隔之内或之外.
I need to parse a time interval expression similar to ISO 8601 syntax, only allowing wildcard for fields; and storing the start and end into two LocalDateTime
objects. My Interval
would then have APIs to compare to a third LocalDateTime
or OffsetDateTime
to check if it falls inside or outside of the interval.
例如:解析"****-**-**T00:00:00Z/****-**-**T11:55:00Z"
时,开始和结束时刻的日期应该是开始执行程序的日期(忽略遇到第二天的问题).我如何解析这样的表达式?
E.g.: when parsing "****-**-**T00:00:00Z/****-**-**T11:55:00Z"
, the date of the start and end instant should be the day of the start program execution (ignoring running into the next day problem). How can I parse an expression like this?
为了清楚起见,如果我今天运行它,它应该等效于解析"2016-04-06T00:00:00Z/2016-04-06T11:55:00Z"
.
to make it clear, if I run it today, it should be equivalent of parsing "2016-04-06T00:00:00Z/2016-04-06T11:55:00Z"
.
推荐答案
我认为没有办法在使用java.time
解析字符串时使用通配符.一个不太好看的技巧是将*
替换为1
:这不应产生任何无法解析的日期.然后,您可以忽略日期内容.
I don't think there is a way to use wildcards when parsing a string with java.time
. A not so good-looking hack would be to replace the *
by 1
: that should not produce any unparseable date. You can then ignore the date content.
例如:
String input = "****-**-01T00:00:00Z/****-04-**T11:55:00Z";
String[] dates = input.replace("*", "1").split("/");
ZonedDateTime zdt1 = ZonedDateTime.parse(dates[0]);
ZonedDateTime zdt2 = ZonedDateTime.parse(dates[1]);
LocalDate day = LocalDate.now(); //or whatever date you like
LocalDateTime start = zdt1.toLocalTime().atDate(day);
LocalDateTime end = zdt2.toLocalTime().atDate(day);
System.out.println(start + " / " + end);
这篇关于具有通配符字段的Java 8 ISO 8601间隔语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!