How come IsDate("13.50") returns True but IsDate("12.25.2010") returns False?
How come IsDate(13.50) returns True but IsDate(12.25.2010) returns False ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I got tripped up by this little “feature” recently and wanted to raise awareness of some of the issues surrounding the
IsDatefunction in VB and VBA.The Simple Case
As you’d expect,
IsDatereturnsTruewhen passed a Date data type andFalsefor all other data types except Strings. For Strings,IsDatereturnsTrueorFalsebased on the contents of the string:IsDateTime?
IsDateshould be more precisely namedIsDateTimebecause it returnsTruefor strings formatted as times:Note from the last two examples above that
IsDateis not a perfect validator of times.The Gotcha!
Not only does
IsDateaccept times, it accepts times in many formats. One of which uses a period (.) as a separator. This leads to some confusion, because the period can be used as a time separator but not a date separator:This can be a problem if you are parsing a string and operating on it based on its apparent type. For example:
The Workarounds
If you are testing a variant for its underlying data type, you should use
TypeName(Var) = "Date"rather thanIsDate(Var):If, however, you are dealing with strings that may be dates or numbers (eg, parsing a text file), you should check if it’s a number before checking to see if it’s a date:
Even if all you care about is whether it is a date, you should probably make sure it’s not a number:
Peculiarities of CDate
As @Deanna pointed out in the comments below, the behavior of
CDate()is unreliable as well. Its results vary based on whether it is passed a string or a number:Trailing and leading zeroes are significant if a number is passed as a string:
The behavior also changes as the decimal part of a string approaches the 60-minute mark:
The bottom line is that if you need to convert strings to date/time you need to be aware of what format you expect them to be in and then re-format them appropriately before relying on
CDate()to convert them.