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.

Santosh A
  • 5,173
  • 27
  • 37
Hash12345
  • 13
  • 2
  • 5
  • 3
    Try to parse it with a `SimpleDateFormat` and see if that works. – Florent Bayle Jan 05 '15 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. –  Jan 05 '15 at 13:20
  • I would test it with a regular expression. For example `[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}`. – Christophe De Troyer Jan 05 '15 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. – Erich Kitzmueller Jan 05 '15 at 13:29

2 Answers2

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
}
brso05
  • 13,142
  • 2
  • 21
  • 40
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;
}
atish shimpi
  • 4,873
  • 2
  • 32
  • 50