2015-12-07 30 views
1

我很新的Java/Android的发展。 我想写一个简单的Android应用程序,并且作为它的一部分,我需要将日期从字符串转换为日期。SimpleDateFormat :: parse()被跳过

我有以下方法:

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(..)从来没有被调用过?

有留在方法的一些调试代码故意

方法调用过程中没有异常被抛出,我通过有效的数据!

+0

抛出异常?重建项目有帮助吗? –

+0

因为它会抛出一个异常... – Selvin

+0

重建多次,没有异常抛出,如果是那么容易,我不会问这个.. –

回答

1

1)你是不是填写日期都:

Calendar cal = Calendar.getInstance(); // <-- this, 
       cal.setTime(format.parse(birthdate)); // and that line gets skipped by debugger step 
       System.out.print(cal); 

您可以设置CAL,而不是日期

2)我称这种方法为 “24/11/1980”,并匹配.matches()返回false,它看起来像if(matcher.matches())中的问题,但调试器会显示错误的行。在将“if(matcher.matches())”更改为“if(true)”后,此方法将打印出“java.util.GregorianCalendar [time = 343868400000,...”。为什么你不使用:

 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; 
    } 

,如果你需要一些验证it'easy具有reg模式的CAL INSEAD做,例如:

   cal.before(new Date()); 
      Calendar beforeHundreadYears = Calendar.getInstance(); 
      beforeHundreadYears.set(1915, 0, 0); 
      cal.after(beforeHundreadYears); 
+0

为什么这么重要?我的问题是关于'format.parse'调用..或缺乏。 –

+0

我将信息添加到我的文章 –

+0

是的,你是对的 - IDE在调试器中显示错误的行 - 它从来没有真正进入'if语句 - 可能因为我正在使用Android Studio的2.0版赌注 –