检查的EditText输入的SimpleDateFormat匹配的Android [英] Check if EditText input matches SimpleDateFormat Android
本文介绍了检查的EditText输入的SimpleDateFormat匹配的Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我搜索了很多关于这一点,但我没有找到一个方法来检查,如果用户在一个EditText写的文字的SimpleDateFormat匹配,有一个简单的办法做到这一点不使用正则表达式?
I've searched a lot about this but I didn't find a way to check if a text written by the user in an EditText matches a SimpleDateFormat, is there a simple way to do that without using regex ?
下面是我的SimpleDateFormat:
Here is my SimpleDateFormat :
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
和我想测试字符串是尊重该格式。
And I want to test if a String respects that format.
推荐答案
我已经找到一种方法通过分析我的串入一个try / catch块的日期来做到这一点。如果字符串可解析,它的SimpleDateFormat匹配:
I've found a way to do this by parsing my string into a date in a try/catch block. If the string is parsable, it matches the 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.
}
这篇关于检查的EditText输入的SimpleDateFormat匹配的Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文