Link to home
Create AccountLog in
Avatar of Ricky White
Ricky WhiteFlag for United States of America

asked on

C# parse DateTime

Hi,

**********************************************************
string str = "20081231113000"

ApplicationDate = DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
****************************************************************
The above code works fine and provides the application date in the format that I need. However sometimes str is blank. In that case the program throws an exception that the string is in invalid format.

How can I change this code so that it will parse and give me the date if available and if the date is unavailable assigns a value of null or minvalue for the applicationdate.

Would a Try Catch be a good approach? or is there a better way?

Thanks
Avatar of Ashok
Ashok
Flag of United States of America image

string str = "20081231113000"

if (String.IsNullOrEmpty(str))
    ApplicationDate = ''
else
    ApplicationDate = DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);

HTH
Ashok
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
@ashok111

string str = "                 ";

Open in new window


Uh-oh!
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
OR

string str = "20081231113000"

if (String.IsNullOrEmpty(str.Trim()))
    ApplicationDate = ''
else
    ApplicationDate = DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);

HTH
Ashok
I agree with kaufmed...TryParseExact() is the way to go.

Besides, you can't assign an empty string to a DateTime!

It's possible to use a NULLABLE DateTime, so it can hold a null, but then you can't use it directly with DateTime.TryParseExact()....   =\
Avatar of Ricky White

ASKER

Thanks!