我是 Java
/Android
开发的新手。
我正在尝试编写一个简单的 Android 应用程序,作为其中的一部分,我需要将日期从字符串转换为日期。
我有以下方法:
private Date convertFromString(String birthdate) {
String regex = "^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$\n";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(birthdate);
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);
if (matcher.matches()) {
try {
Calendar cal = Calendar.getInstance(); // <-- this,
cal.setTime(format.parse(birthdate)); // and that line gets skipped by debugger step
System.out.print(cal); // this line gets executed
} catch (ParseException exception) {
System.out.print("wtf??");
}
}
return date;
}
无论传递给方法的字符串值如何,它始终返回 null
。当我单步执行带有上面标记的调试器行的代码时,调试器会跳过它,它不会让我介入,就好像从未调用过 format.parse(..)
一样?
故意在方法中留下一些调试代码
方法调用没有异常,我传入的是有效数据!
最佳答案
1) 你根本没有填写日期:
Calendar cal = Calendar.getInstance(); // <-- this,
cal.setTime(format.parse(birthdate)); // and that line gets skipped by debugger step
System.out.print(cal);
你设置了日历,但没有设置日期
2) 我用“24/11/1980”调用此方法,matcher.matches() 返回 false,它看起来像 if(matcher.matches()) 中的问题,但调试器显示错误行。在我将“if(matcher.matches())”更改为“if(true)”之后,此方法打印“java.util.GregorianCalendar[time=343868400000,...”。为什么你不使用 just:
private Date convertFromString(String birthdate) {
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);
try {
Calendar cal = Calendar.getInstance(); // <-- this,
cal.setTime(format.parse(birthdate)); // and that line gets skipped by debugger step
System.out.print(cal); // this line gets executed
return cal.getTime();
} catch (ParseException exception) {
System.out.print("wtf??");
}
return null;
}
?
如果您需要一些验证,使用 cal insead of reg pattern 很容易,例如:
cal.before(new Date());
Calendar beforeHundreadYears = Calendar.getInstance();
beforeHundreadYears.set(1915, 0, 0);
cal.after(beforeHundreadYears);
关于java - SimpleDateFormat::parse() 被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34144468/