问题
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.
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?
EDIT: 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"
.
回答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.
For example:
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);
来源:https://stackoverflow.com/questions/36456242/java-8-iso-8601-interval-syntax-with-wildcard-fields