Why this doesn't work?

K

KK

Hi,

I want my users to be able to enter date in any format. Such as
dd/mm/yyyy, mm/dd/yyyy etc...

then I use the following method to see wether this is
a valid date :

try
{
DateTime NewDate = DateTime.Parse("16/11/1976");
return true;
}
catch(FormatException ex)
{
return false;
}

but this always gives me a format exception. My computer
date format is in mm/dd/yyyy , but the date i am trying
to validate is in dd/mm/yyyy. Can't the parse method
recognize that this input date is in dd/mm/yyyy format?

rgds
KK
 
J

Jon Skeet [C# MVP]

KK said:
I want my users to be able to enter date in any format. Such as
dd/mm/yyyy, mm/dd/yyyy etc...

then I use the following method to see wether this is
a valid date :

try
{
DateTime NewDate = DateTime.Parse("16/11/1976");
return true;
}
catch(FormatException ex)
{
return false;
}

but this always gives me a format exception. My computer
date format is in mm/dd/yyyy , but the date i am trying
to validate is in dd/mm/yyyy. Can't the parse method
recognize that this input date is in dd/mm/yyyy format?

It doesn't by default - and I think this is a good thing, as otherwise
it wouldn't know what to do if you gave it 06/05/1976.

Use DateTime.ParseExact with the right format.
 
S

Shakir Hussain

kk,

you have to define culture info to parse that

try this

DateTime NewDate = DateTime.Parse("16/11/1976", new
System.Globalization.CultureInfo("en-GB",true),
System.Globalization.DateTimeStyles.NoCurrentDateDefault);

"en-GB" is English-UK

Shak.
 

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

Similar Threads


Top