我正在考虑创建一个应该返回有效日期数的方法。如何使用简单日期格式?
class ValidatorDate {
public static int ValidDates(String[] words) {
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
format.setLenient(false);
}
}
public class Main {
public static void main(String[] args) {
System.out.println(ValidatorDate.ValidDates(new String[]{"car","bench","01/04/2019",
"01/13/2019", "29/02/200s"}));
// 2
}
}
您可以在try/catch
块中解析每个日期及其数字,并按如下方式递增计数器:
public static void main(String[] args) {
String[] dates = new String[]{"car","bench","01/04/2019", "01/13/2019", "29/02/200s"};
System.out.println(validate(dates));
}
private static int validate(String[] dates){
int count = 0;
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
format.setLenient(false);
for(String date : dates) {
try {
format.parse(date);
String[] dateParts = date.split("/");
for(String str : dateParts)
Integer.parseInt(str);
if(dateParts.length!=3 || dateParts[0].length()!=2 || dateParts[1].length()!=2 || dateParts[2].length()!=4)
throw new Exception();
count++;
} catch (Exception e) {
System.out.println("Date " + date + " is not valid");
}
}
return count;
}
输出:
Date car is not valid
Date bench is not valid
Date 01/13/2019 is not valid
Date 29/02/200s is not valid
1
编辑:根据 Ole 的评论和这篇文章,最好使用更准确的库:
public static void main(String[] args) {
String[] dates = new String[]{"car","bench","01/04/2019", "01/13/2019", "29/02/200s"};
System.out.println(validate(dates));
}
private static int validate(String[] dates){
int count = 0;
for(String date : dates) {
try {
String[] dateParts = date.split("/");
if(dateParts.length==3 && isDateValid(Integer.parseInt(dateParts[2]), Integer.parseInt(dateParts[1]), Integer.parseInt(dateParts[0])))
count++;
else
throw new Exception();
} catch (Exception e) {
System.out.println("Date " + date + " is not valid");
}
}
return count;
}
private static boolean isDateValid(int year, int month, int day) {
boolean dateIsValid = true;
try {
LocalDate.of(year, month, day);
} catch (DateTimeException e) {
dateIsValid = false;
}
return dateIsValid;
}