2015-12-07 45 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版賭注 –