Check if field contains a date

Asked

Viewed 177 times

0

I have a list of a EditText's which are filled with data returned from the database.

Some have a common text, for example

<EditText
      android:id="@+id/edittext"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Jon Snow" />

And in other cases it may be a date:

<EditText
      android:id="@+id/edittext"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="2017-06-20" />

How could I check if the text being displayed on EditText is a date or other common text? Does a regex would solve this?

  • You need to know if it is a date in the Edittext fill-in (when pulling the data from the database), or at some other time?

1 answer

1

public static boolean isValidaData(String dataStr){
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); //Formate a data do jeito que for necessário, outro exemplo: ("dd/MM/yyyy")
    try {
        java.sql.Date data = new java.sql.Date(format.parse(dataStr).getTime());
        return true;
    } catch (ParseException ex) {
        return false;
    }
}

Then just call the method:

boolean dataValida = isValidaData(meuEditText.getText().toString());

Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.