AMagic
AMagic

Reputation: 2810

Check if month or day or year is in range of two dates

I have a filter that is a String and can only accept 3 date-formats - YYYY, YYYY-MM, YYYY-MM-DD.

I want to check if the requested String is in the range of two dates.

Let's say, I have two dates (Instants) in a record - 2010-05-01T00:00:00Z & 2020-03-01TT23:59:59.999999999Z

Then:

Requested date | Range result

2018 | in range

2010 | in range

2009 | NOT in range

2018-03 | in range

2010-02 | NOT in range

2010-05 | in range (Thanks for the correction @Ole V.V.)

2012-01-05 | in range

2020-03-01 | in range

2020-04-01 | NOT in range

I am using Java time to check if a date is before or after the given dates, but in my case, I have a string that could be in any of the 3 date-formates.

One solution I can think of is if the request is YYYY, then only check if it is between years of the two dates. If the request is YYYY-MM, then check if it is between Year and month of the two dates. And so on. But I am not sure how to make it work.

Can someone please help to solve this problem?

Upvotes: 1

Views: 1671

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

You can create your own method to check if your date is valid of not, in your problem, you have three different cases, date which have only year, or date which have only year and month, or a full date, in this cases, you have a small problem when you want to parse the only the year, I can gives you this solution :

public static boolean isValid(String date, Instant start, Instant end) {
    LocalDate sld = start.atOffset(ZoneOffset.UTC).toLocalDate();
    LocalDate eld = end.atOffset(ZoneOffset.UTC).toLocalDate();
    try {
        LocalDate ld = LocalDate.parse(date);
        return ld.isAfter(sld) && ld.isBefore(eld);
    } catch (DateTimeParseException e) {}

    try {
        YearMonth ym = YearMonth.parse(date);
        return ym.isAfter(YearMonth.from(sld)) && ym.isBefore(YearMonth.from(eld));
    } catch (DateTimeParseException e) {}

    try {
        Year y = Year.parse(date);
        return y.isAfter(Year.from(sld)) && y.isBefore(Year.from(eld));
    } catch (DateTimeParseException e) {}
    return false;
}

Here is an Idemo demo

Upvotes: 3

Related Questions