Link to home
Start Free TrialLog in
Avatar of Murray Brown
Murray BrownFlag for United Kingdom of Great Britain and Northern Ireland

asked on

ASP.net web forms C# Convert string to date

Hi

In my ASP.net C# web forms project I want to write a method that converts a string value into text. If it is not a  date I am not sure what to do. Should I just set some date far in the past. I am trying to return a null value


        public DateTime ConvertToDate(string oText)

        {

            DateTime dDate;

            if (DateTime.TryParseExact(oText, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out dDate))

            {

                return dDate;

            }

            else

            {

                return System.DateTime.Null;

            }

        }


ASKER CERTIFIED SOLUTION
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Your current implementation of the method is hardcoded to "yyyy-MM-dd", If your method accepts an argument in a different format, it would return Null. If you're concerned about the Null, you could return DateTime.MinValue and then check in the outer method if the value of the datetime object is greater than MinValue. But to be honest, I think the best way would be to use the TryParseExact directly instead of wrapping it inside another method, so you could just check the boolean returned from it and then control the flow accordingly.