Avatar of Ricky White
Ricky White
Flag 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
C#.NET ProgrammingVisual Basic.NET

Avatar of undefined
Last Comment
Ricky White

8/22/2022 - Mon
Ashok

string str = "20081231113000"

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

HTH
Ashok
ASKER CERTIFIED SOLUTION
kaufmed

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
kaufmed

@ashok111

string str = "                 ";

Open in new window


Uh-oh!
SOLUTION
Ashok

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Ashok

OR

string str = "20081231113000"

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

HTH
Ashok
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Mike Tomlinson

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()....   =\
Ricky White

ASKER
Thanks!