turtleboy
turtleboy

Reputation: 7572

How to check if a String is a valid Joda DateTime

I have the follwing String stored in my DB

cursor.getString(cursor.getColumnIndex(C_TAG_SENTSERVER_TIME);

.

How can i test to see if the String is a valid Joda DateTime. The String is for example 11236263722, basically a long.

I'd like to check that the String is not for example ",kjj", as this would not be valid.

i've tried the following.

public boolean isValidDate(String dateString) {

        Log.e(TAG, "dateString (sentToServerTime under test) =========>>>>>>>> " + dateString);

            if(DateTime.parse(dateString) != null){

                Log.e(TAG, "sent to server time is valid");
                return true;

            }else{

                Log.e(TAG, "sent to server time is not valid");
                return false;

            }

    }

Upvotes: 1

Views: 4096

Answers (1)

Meno Hochschild
Meno Hochschild

Reputation: 44061

I have no idea what kind of format "11236263722" is. Is it the count of seconds or milliseconds since 1970??? It does not look like this. Anyway, if you just want to ensure that you have a "long" that is only digits, then following simple approach might be sufficient for you.

String test = "11236263722";

public boolean isValid(String test) {
  for (int i = 0, n = test.length(); i < n; i++) {
    char c = test.charAt(i);
    if (c < '0' || c > '9') {
      return false;
    }
  }
  return true;
}

But if your date string is in any specialized date/time pattern, then you have to specify the exact and expected pattern like this:

  public boolean isValid(String test) {
    try {
      DateTimeFormatter dtf = DateTimeFormat.forPattern("{your pattern}");
      dtf.parseDateTime(text);
      return true;
    } catch (IllegalArgumentException iae) {
      return false;
    }
  }

Upvotes: 2

Related Questions