问题
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 ?
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.
回答1:
You may use a TextWatcher
to listen input changes to your EditText
and may perform appropriate actions in either of its provided method.
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
}
});
回答2:
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.
}
来源:https://stackoverflow.com/questions/16401748/check-if-edittext-input-matches-simpledateformat-android