Validate DateTime

S

shapper

Hello,

I need to validate a string containing a date, time or datetime. A few
examples:

1. Check if "2008-27-10" is in the format "yyyy-MM-dd" ... in this
case is false.

2. Check if "2008-27-10 20:30:30" is in the format "yyyy-dd-MM
hh:mm:ss" ... in this case is true.

Is there a way to do this?

I only need to return true or false.

Thanks,
Miguel
 
S

shapper

See DateTime.TryParseExact().

Pete

I came up with:

try
{
DateTime test = DateTime.ParseExact(value, format,
null);
return true;
}
catch (Exception ex)
{
return false;
}

Where value is the datetime string to test and format is for example
"yyyy-dd-MM HH:mm:ss"

I was checking but it seems I always need to provide a culture?
 
S

shapper

See DateTime.TryParseExact().

Pete

I was also trying:

DateTime result;
return DateTime.TryParseExact(value, format, null,
CultureInfo.InvariantCulture, out result);

But I get the error:
The best overloaded method match for 'System.DateTime.TryParseExact
(string, string, System.IFormatProvider,
System.Globalization.DateTimeStyles, out System.DateTime)' has some
invalid arguments

I am not sure how to solve this ... I think the problem is in third
argument which is IFormatProvider but I am not sure what to place
here.
 
S

shapper

I was also trying:

      DateTime result;
      return DateTime.TryParseExact(value, format, null,
CultureInfo.InvariantCulture, out result);

But I get the error:
The best overloaded method match for 'System.DateTime.TryParseExact
(string, string, System.IFormatProvider,
System.Globalization.DateTimeStyles, out System.DateTime)' has some
invalid arguments

I am not sure how to solve this ... I think the problem is in third
argument which is IFormatProvider but I am not sure what to place
here.

I was able to solve it using:
DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out result);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top