Testing for valid date?

Dear Experts,

This is an easy one (I hope).

Given a String, what is the elegant way to test if it contains a valid CCYYMMDD date?  I know I can parse it by hand, but is there a simpler way,  using Calendar, for instance?

Thanks,
BrianMc1958
BrianMc1958Asked:
Who is Participating?
 
tbeernotConnect With a Mentor Commented:
public static void main(String[] args)
{
      try
      {
            SimpleDateFormat lSimpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            System.out.println(lSimpleDateFormat.parse("20071231"));
      }
      catch (Throwable t)
      {
            t.printStackTrace();
      }
}
0
 
tbeernotCommented:
Use SimpleDateFormat
0
 
BrianMc1958Author Commented:
I'm trying it, but I'm not getting it to work with "20071231", for instance.
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
BrianMc1958Author Commented:
That compiles and runs.  However, it accepts "20071232".  (It decides that equals 20080101).  If nobody else responds, I'll award points anyway, but I'd like to wait a little while longer.

Would you have another suggestion that would validate the month and day?
0
 
tbeernotCommented:
This is the behavior of the Java parsers. Otherwise you have to do it yourself.
0
 
BrianMc1958Author Commented:
To anyone reading this, add this line to the above:

                  lSimpleDateFormat.setLenient(false);

It works.

Thanks very much...
0
 
tbeernotCommented:
setLenient... Interesting. Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.