我对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(..)
从来没有被调用过一样?
方法中有一些调试代码是有意的
在方法调用期间没有异常抛出,我传递有效的数据!
发布于 2015-12-07 22:39:23
( 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)”后,此方法将打印matcher.matches.。你为什么不使用:
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;
}
?
如果您需要进行一些验证,例如,它可以对reg模式的cal insead进行验证:
cal.before(new Date());
Calendar beforeHundreadYears = Calendar.getInstance();
beforeHundreadYears.set(1915, 0, 0);
cal.after(beforeHundreadYears);
https://stackoverflow.com/questions/34144468
复制相似问题