У меня этот метод isFormatDateCorrect, чтобы вернуть true, если этот формат ([email protected]
) даты верен, и эти методы являются правильными.манипулировать строкой date в Java
public boolean isFormatDateCorrect(String date) {
if (date == null || date.length() == 0) {
return false;
} //[email protected]
return date.matches("([0-9]{4})@([0-9]{4})-([0-9]{2})-([0-9]{2})");
}
и здесь у меня есть другие методы isValidDate, но у меня есть ошибки, когда я получаю номер процесса, и год, месяц и день, я использую date.substring(); но это методы возвращают только ложные
public boolean isValidDate(String date) {
int process_number, day, month, year, max_days = 0;
if (date == null || date.length() == 0) {
return false;
}
//The correct format of date is [email protected]
if (isFormatDateCorrect(date) != true) {
return false;
}
//[email protected]([email protected])
process_number = Integer.parseInt(date.substring(0, date.indexOf("@")));//get process number
year = Integer.parseInt(date.substring(date.indexOf("@") + 1, date.indexOf("-")));// get year
month = Integer.parseInt(date.substring(date.indexOf("-") + 1, date.lastIndexOf("-")));// get month
day = Integer.parseInt(date.substring(date.lastIndexOf("-") + 1, date.lenght()));//get day
if (month < 1 || month > 12) {
return false;
} else {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
max_days = 31;
break;
case 4:
case 6:
case 9:
case 11:
max_days = 30;
break;
case 2:
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
max_days = 29;
} else {
max_days = 28;
}
break;
}
if (day < 1 || day > max_days) {
return false;
}
}
return true;
}
Для Exemple в Main, когда я испытываю
String date = "[email protected]"
if(isValidDate(date) != true){
System.out.println("This date is invalid");
}else{
System.out.println("This date is valid");
}
и выход:
System.out.println ("Эта дата инвалид");
Зачем изобретать колесо? Используйте «SimpleDateFormat» для проверки правильности даты (после удаления номера процесса и @). –
Это тип проблемы, которую можно легко решить, пройдя через отладчик – jalynn2