我输入的字符串转换为日期格式。当我尝试给出两个日期作为输入Date of Birth
和Date of Joining
,我没有得到任何满意的结果。如果输入无效,也可以帮助我重新提示。提前致谢。日期有两个日期
public class EmployeeInfo {
int id;
static String name, DoBS, DoJS;
Date DoB, DoJ;
public void checkDate(String dt) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat sdf3 = new SimpleDateFormat("dd MMMM yyyy");
Date date = null;
try {
date = sdf1.parse(dt);
} catch (ParseException e) {
try {
date = sdf2.parse(dt);
} catch (ParseException e1) {
try {
date = sdf3.parse(dt);
} catch (ParseException e2) {
String invalid="Invalid,Retry";
System.out.println(invalid);
// TODO: Whatever to do when it doesn't find a date
}
}
}
setDateOfBirth(date);
setDateOfJoining(date);
}
void setDateOfBirth(Date DoB) {
this.DoB = DoB;
}
void setDateOfJoining(Date DoJ) {
this.DoJ = DoJ;
}
void print() {
System.out.println("User ID: " + id);
System.out.println("Name: " + name);
System.out.println("Date Of Birth: " + DoB);
System.out.println("Date of Joining: " + DoJ);
}
public static void main(String[] args) throws ParseException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name: ");
name = scanner.nextLine();
System.out.println("Enter the Date Of Birth: ");
DoBS = scanner.nextLine();
System.out.println("Enter the Date of Joining: ");
DoJS = scanner.nextLine();
EmployeeInfo e = new EmployeeInfo();
e.checkDate(DoBS);
e.checkDate(DoJS);
e.print();
}
}
你不需要内为''try' try' –
输入的姓名,出生日期和加入的日期。我想把这些东西打印回来。日期验证的东西.. –
代码将是这样多少“冷”,如果你有使用一些方法“的TryParse”或类似的东西 – 2017-08-02 11:31:02