Reputation:
I have an ArrayList
as below:
dates : [
"1981-1990",
"1971-1980",
"1991-2000"
]
I would like to perform a check: to see if the values in the list are year-ranges or not.
EDITED : Sometimes I get proper dates format like 'yyyy-MM-dd' and sometimes year-range. I just want my function to work in both conditions. It should identify it as a date if a date is present or year range. That's all
Upvotes: 1
Views: 211
Reputation: 60046
You can use Year with Year::isBefore from java-time api like so :
String[] ranges = {"1981-1990", "1971-1980", "1991-2000"};
for (String range : ranges) {
String[] dates = range.split("-");
if (Year.parse(dates[0]).isBefore(Year.parse(dates[1]))) {
System.out.println("Correct range");
} else {
System.out.println("Wrong range");
}
}
After your edit, I would go with this solution here :
String[] dates = {"1981-1990", "2020-02-25", "1971-1980", "1998-02-25", "1991-2000"};
for (String date : dates) {
if (date.matches("\\d{4}-\\d{4}")) {
String[] split = date.split("-");
if (Year.parse(split[0]).isBefore(Year.parse(split[1]))) {
System.out.println("Correct range");
} else {
System.out.println("Wrong range");
}
} else {
try {
LocalDate.parse(date);
System.out.println("Correct date");
} catch (DateTimeParseException ex) {
System.out.println("Wrong date");
}
}
}
Upvotes: 4
Reputation: 77063
Your ArrayList
has String
elements, so, you need to call the .split() method for each of them while you are looping your ArrayList
. The split
method returns an array of strings, so, on the resulting array you check the length. If the length is 2, then you have two years. If the length is 5, then you have two full dates. If the length is 4, then one of the values is a full date and the other is a year. So,
for (int index = 0; index < myArrayList.size(); index++) {
String[] items = myArrayList.get(index).split();
if (items.length == 2) {/*Two years*/}
else if (items.length == 5) {/*Two full dates*/}
else if (items.length == 4) {
if (items[1].length() == 4) {/*The first is a year, the second a full date*/}
else {/*The first is a full date, the second is a year*/}
}
}
Upvotes: 0