tags:

views:

154

answers:

4

I receive Date and time from CSV file

The received Date format is  YYYYMMDD (string) (there is no ":" ,"-","/" to 
separate  Year month and date).

The received time format is HH:MM (24 Hour clock).

I have to validate both so that (example) (i) 000011990 could be invalidated for date (ii) 77:90 could be invalidated for time.

The question is ,

Regular expression is the right candidate for do so (or) is there any other way to achieve it?

+2  A: 

I think a better way would be to use the date format class built into C#: DateTime.parse

duffymo
+4  A: 

Your easiest solution would be to use

DateTime output;
if(!DateTime.TryParse(yourstring, out output))
{ 
   // string is not a valid DateTime format
}

The DateTime.TryParse will attempt to convert your string to a DateTime variable, but it won't throw an exception if it fails - rather it return false if the string is not recognized as a valid DateTime.

marc_s
`ParseExact` might be a better option, though, since the format is known beforehand and `TryParse` (like `Parse`) tries whatever `DateTime` might recognize which may or may not be the right thing to do.
Joey
Well, the question is probably more along the lines of »Is it an error if the date format isn't like previously specified.« Might violate Postel's law, though but in some cases `ParseExact` is probably still better to only accept a single valid representation. (Which imho should always be ISO 8601 but that's probably just my twisted, weird mind :-))
Joey
@Johannes Rössel: or see SLaks' answer - use `TryParseExact` instead of just TryParse....
marc_s
+1  A: 

You can use one of the TryParse methods of the DateTime struct. They will return false if they fail to parse.

Another option it use the ParseExact methods, but for those you need to specify a format provider.

Oded
You can pass `null` as the format provider, though.
Joey
@Johannes Rössel - Fair point :)
Oded
+8  A: 

You're looking for DateTime.TryParseExact:

string source = ...;
DateTime date;
if (!DateTime.TryParseExact(source, 
                            "yyyyMMdd", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None, 
                            out date)) {
    //Error!
}

You can use the same code to validate times, with the format string "HH:mm".

SLaks
+1 I'll be darned.... why didn't I ever see that before?? Thanks for pointing that out !!
marc_s
Opps ! Brilliant ! Thank you very much