[英]How to check if a string is of yyyy-yyyy format
I have an ArrayList
as below:我有一个ArrayList
如下:
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.编辑:有时我会得到正确的日期格式,如“yyyy-MM-dd”,有时会得到年份范围。 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就这样
You can use Year with Year::isBefore from java-time api like so :您可以使用Year和Year::isBefore从java-time api 像这样:
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");
}
}
}
Your ArrayList
has String
elements, so, you need to call the .split() method for each of them while you are looping your ArrayList
.您的ArrayList
具有String
元素,因此,您需要在循环ArrayList
时为每个元素调用.split()方法。 The split
method returns an array of strings, so, on the resulting array you check the length. split
方法返回一个字符串数组,因此,在结果数组上检查长度。 If the length is 2, then you have two years.如果长度为 2,则您有两年时间。 If the length is 5, then you have two full dates.如果长度为 5,则您有两个完整的日期。 If the length is 4, then one of the values is a full date and the other is a year.如果长度为 4,则其中一个值为完整日期,另一个值为年份。 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*/}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.