Re: Parsing strings to other datatypes without throwing exceptions

From: Christof Nordiek (Christof.Nordiek_at_gmx.de)
Date: 06/25/04


Date: Fri, 25 Jun 2004 09:18:26 +0200

Hallo Mike,

you could try something like this:
string dateString = ......

int day = int.Parse(dateString.Substring(0,2));

int month = int.Parse(dateString.Substring(2,2));

int year = int.Parse(dateString.Substring(4,4));

bool isDate;

if (DateTime.DaysInMonth(year,month) < day)

isDate = false;

else

isDate = true;

"MikeG" <mgriffiths@compasscc.com> schrieb im Newsbeitrag
news:3c8932cc.0406240444.22cc82fc@posting.google.com...
> Hi,
>
> I want to be able to check that a string is of a desired format
> particularly datetime strings.
>
> VB IsDate() function doesn't work becuase it doesn't know what format
> my date is supposed to be. E.g. whist '20031010' maybe a valid date if
> the expected format is 'yyyyMMdd' it's not valid if the expected
> format is 'ddMMyyyy'.
>
> I've looked at using the DataTime.ParseExact(...) because I can then
> specify the exact format my date is in.
>
> But I don't want an "exception" to happen becuase this is bad for
> performance.
> (I'm importing data from large files and need to report formating
> problems with line numbers etc. whenever a badly formatted field is
> encountered.)
>
> What I want is this VB.NET code:
> Function IsDateTimeValidFormat(value As String, format As String) As
> Boolean
>
> One idea I had is ... I noticed from the stack trace of the ParseExact
> function that it is calling into some private class called
> ParseDateTime or somthing like that, could/should I use reflection to
> call into this class?
>
> thanks in advance for any help/suggestions,
> MikeG



Relevant Pages