Skip to content Skip to sidebar Skip to footer

Check If Edittext Input Matches Simpledateformat Android

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 us

Solution 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
    }
});

Solution 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 {
    SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Stringdate= ((EditText) findViewById(R.id.editTextDate)).getText().toString(); // EditText to check
    java.util.DateparsedDate= dateFormat.parse(date);
    java.sql.Timestamptimestamp=newjava.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.        
}

Post a Comment for "Check If Edittext Input Matches Simpledateformat Android"