Question:
Java validate Date Format?
IneedAnswers
2009-04-25 09:52:10 UTC
If i have someone tpying in a date into a text box how do I validate that the date format entered is MM/DD/YY in my set method?

public boolean setTimeDate(String timeDate)

Date date = new Date();

{
DateFormat df = formatter = new SimpleDateFormat("Mm/dd/yy");
timeDate = formatter.format(date);

//Date date new Date = results.getDate(column);
// DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

//System.out.println("Formatted date: " + df.format(date));


}
Three answers:
deonejuan
2009-04-25 11:06:36 UTC
Now you know why good GUI will use popup lists or a calendar widget!!!



Incidentially, Date is deprecicated. Use the static method of Calendar to get going.



Calendar today = Calendar.getInstance();

today.set(yyyy,mm,dd);

yyyy = 4-digit integer

mm = 0-11, array of the months, 0 = january, 11 = december

dd = 1-31

for whatever reason 04 is legal in months

but 01 is NOT legal in days. go figure.



Date.format() will then take the Calendar Object and format it to your ideal of what a proper date should be -- as a String.



I would have to know more about what you are trying to do. Time seems to be the most mangled concept with junior programmers.
anonymous
2009-04-25 17:48:22 UTC
You can use a regular expression like this...



import java.util.regex.Matcher;

import java.util.regex.Pattern;

...

Pattern datePattern = Pattern.compile("\\d{2})-(\\d{2})-(\\d{2}");

Matcher dateMatcher = datePattern.matcher(aDate);

if (!dateMatcher.find())

{

throw new ValidationException("Bad date format");

}



But this won't tell you if it is really a date.



I think it is better to parse the date using a SimpleDateFormatter:



DateFormat sdf = new SimpleDateFormat("MM/dd/yy");

Date d = sdf.parse(dateString);



If the dateString is invalid, then the DateFormat object will throw a parse exception.
Bravo!
2009-04-25 17:10:51 UTC
Instead of using DateFormat, do you have the option of:

(a) breaking down the string into individual MM, DD and YY strings using StringTokenizer and

(b) determining that each of MM, DD and YY are valid?



SimpleDateFormat has a parse(), but I do not know if it will work for you.

http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...