Parsing strings to other datatypes without throwing exceptions

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
 
D

David Browne

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
 
C

Christof Nordiek

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;
 

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