Regex Date and Time Validation

Hello,
Please help me with Regex for the following date formats in java:

1. MM/dd/yyyy

2. yyyy/MM/dd

it should validate the date considering all the things: like months of 30 and 31 days and 28 days and 29 days, month fld should not be > 12 and so on.
Time Formats:

1.  hh:mm  12 hour format.

Thanks
panshul007Asked:
Who is Participating?
 
Gurvinder Pal SinghCommented:
You can find a lot of examples here
http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5

for 2), this might be the regular expression you are looking for
http://www.regular-expressions.info/dates.html

But i would suggest using Simple Date format to do this for you

String strDate =""
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

Date date = formatter .parse( strDate);



If there is any validation issue, it will throw exception by itself
0
 
ksivananthCommented:
it would be difficult using regex, better you capture the date string using regex and validate using SimpleDateFormat, check the example, http://www.dreamincode.net/forums/showtopic14886.htm
0
 
panshul007Author Commented:
Please give me Regex for time format atleast...
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
ksivananthCommented:
MM\dd\yyyy - "\\d{2}\\\\\\d{2}\\\\\\d{4}"
0
 
Gurvinder Pal SinghCommented:
For time format
^(([0]?[0-5][0-9]|[0-9]):([0-5][0-9]))$

If you explore the link that i had given earlier, many examples are given, which may interest you

Thanks
0
 
objectsCommented:
0
 
pavanshahiCommented:
0
 
panshul007Author Commented:
for time this regex worked: (1[012]|0[1-9]|[1-9]):[0-5][0-9]

for date I used the date formater util and put it in a try catch.... if it was unsuccessful in converting i.e not a valid date format... so generated error in catch....

actually i am validating my web service.

0
 
panshul007Author Commented:
the expert comment by object was the most helpful...
it gave me the actual idea for validating the date...

actually i am validating my web service...

and gurwinder thanks for the date formatter idea..

Although i had to modify everything to get the actual date validation that included the 30 and 31 days check and leap year check...

and time validation i had to make myself.
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.