Parsing strings to other datatypes without throwing exceptions

  • Thread starter Thread starter MikeG
  • Start date Start date
M

MikeG

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
 
MikeG said:
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?

Your concern about the cost of exceptions is probably overblown, but look at
Regular expressions (System.Text.RegularExpressions), for testing the
formatting of strings.

David
 
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;
 
Back
Top