2013-05-06 98 views
0

我已經搜索了很多關於此的內容,但是我沒有找到一種方法來檢查用戶在EditText中編寫的文本是否與SimpleDateFormat匹配,是否有一種簡單的方法可以做到這一點不使用正則表達式?檢查EditText輸入是否與SimpleDateFormat匹配Android

這裏是我的SimpleDateFormat:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

我想測試字符串是尊重該格式。

+0

定義 「的TextFormat」 – njzk2 2013-05-06 15:41:28

+0

我有錯的SimpleDateFormat爲的TextFormat。我想與用戶編寫的文本進行比較的一個是:'SimpleDateFormat dateFormat = new SimpleDateFormat(「yyyy-MM-dd-HH.mm.ss」);' – Glrd 2013-05-07 12:22:00

回答

0

我已經找到了一種方法來解析我的字符串到try/catch塊中的日期。如果字符串可解析,它的SimpleDateFormat匹配:

try { 
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    String date = ((EditText) findViewById(R.id.editTextDate)).getText().toString(); // EditText to check 
    java.util.Date parsedDate = dateFormat.parse(date); 
    java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime()); 
    // If the string can be parsed in date, it matches the SimpleDateFormat 
    // Do whatever you want to do if String matches SimpleDateFormat. 
} 
catch (java.text.ParseException e) { 
    // Else if there's an exception, it doesn't 
    // Do whatever you want to do if it doesn't.   
} 
2

您可以使用TextWatcher來傾聽對您的EditText的輸入更改,並可以按其提供的任一方法執行適當的操作。

yourEditText.addTextChangedListener(new TextWatcher() { 

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
    } 

    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, 
     int after) { 
    } 

    @Override 
    public void afterTextChanged(Editable s) { 
     //you may perform your checks here 
    } 
}); 
+0

我已經測試過TextWatcher,但是它的afterTextChanged方法在每個字符更改後調用,所以我使用了onFocusChangedListener,而沒有問題。這是比較用戶寫的日期(字符串)與我想要的SimpleDateFormat。 – Glrd 2013-05-07 12:29:03

相關問題