2013-05-06 50 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

相关问题