Date formatting

  • Thread starter Thread starter Leszek
  • Start date Start date
L

Leszek

Hello,

I believe there must be somwhere in .NET a method to easily deal with the
following situation:
1. A user enters a date (myDate) in a format dd/mm/yyyy
2. A method checks if the myDate is properly formatted

The method might look like this:
isCorrect = IsDateCorrect(myDate, "dd/mm/yyyy");

isCorrect == true - myDate is formatted properly
isCorrect == false - myDate has any incorrect characters (letters), or it is
incorrect (5/13/2003 - 13th month, or 30/2/2003), or it is formatted
inproperly (10/11-2003 or 1/1/98)

Is there somewhere such a IsDateCorrect function available?

Thanks,
Leszek Taratuta
 
Not as far as I know.

Trivial to write though:

bool IsDateCorrect( string date, string format )
{
try
{
DateTime dt = DateTime.Parse( date );
// a date but is it in required format
return (date == dt.ToString(format);
}
catch
{
// not a valid date
return false;
}
}

I'm sure others can improve.

HTH
Charles
 
Thanks.
I wish this method worked, but unfortunately it does not give proper
results.
I tried the format dd/mm/yyyy to check a date 15/03/2003.
The DateTime.Parse() function switches day and month, so dt = 3/15/2003.
Then the ToString() method tries to interpret 15 as a month, so the result
is dt.ToString("dd/mm/yyyy") = 00/15/2003.

That's the problem.

Any suggestions?

Leszek Taratuta
 
Hi Leszek,

I apologize for it if there is any misunderstanding. Please try the
following code snippet on your side.

...
System.IFormatProvider format =
new System.Globalization.CultureInfo("fr-FR", true);

string strMyDateTimeFrench = "15/03/2003";
System.DateTime myDateTimeFrench;

try
{

myDateTimeFrench =
System.DateTime.Parse(strMyDateTimeFrench,
format,
System.Globalization.
DateTimeStyles.NoCurrentDateDefault);
}
catch (System.Exception myError)
{
Response.Write(myError.Message);
return;
}
string result =
myDateTimeFrench.Day.ToString() + "/" +myDateTimeFrench.Month.ToString()
+"/"+myDateTimeFrench.Year.ToString();
Response.Write(result);
...

Does it answer your question? If I have misunderstood your concern, please
feel free to let me know.

Best regards,

Jacob Yang
Microsoft Online Partner Support
Get Secure! ¨C www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Back
Top