1

Is their a method in java to check weather a given string is Date or not.
example:

 String s="Hello"              //is not Date <br>
 String s="01/05/2014"         //is a valid date 

thank You.

4
  • 3
    Try to parse it with a SimpleDateFormat and see if that works. Commented Jan 5, 2015 at 13:18
  • Florent Bayle's solution is perfect if the format is known pre-parsing. If OP is looking for a universal dateValidator much like PHP's (utterly broken) strtotime then I'm afraid he's out of luck. Commented Jan 5, 2015 at 13:20
  • I would test it with a regular expression. For example [0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}. Commented Jan 5, 2015 at 13:21
  • I think a two-step solution is in many situations preferable: First, use the regex (@ChristopheDeTroyer) to check if the string looks like a date; if it matches, use SimpleDateFormat.parse to verfiy that it is a valid date. Commented Jan 5, 2015 at 13:29

2 Answers 2

2

You can check for a specific format using SimpleDateFormat ex:

DateFormat df = new SimpleDateFormat("mm/dd/yyyy");

try
{
   df.parse("01/05/2014");
}
catch(Exception e)
{
  //not a date
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would rather catch for ParseException.
@Journeycorner that is fine too you can catch whatever exception you want
@brs05: It would hide (runtime)exceptions. Imagine the input is null, doing it your way the NullPointerException would also be caught - not the finest way imho.
2

Write simple API that will validate string is date or not,

If isValidDate(String date) return true then your string is date otherwise it is not date.

public boolean isValidDate(String date){
   SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");
   boolean flag = true;

   try{
      dateFormat.parse(date); 
   }catch(ParseException e){
      flag = false;
   }
 return flag;
}

1 Comment

Don't catch Exception, try ParseException instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.