Further to solution 1.
You've tagged C# in your question so you can't use
CDate(selected_date)
- that is a VB function (there
are ways of using VB.NET functions in C# but I'm not going to say how)
There are a few ways of converting strings to dates and some are better than others in certain circumstances.
Let's start with
Convert.ToDateTime
DateTime d1 = Convert.ToDateTime(selected_date);
will work with the text you have in your example (which is one of the better ways of passing dates around)
But what if
string selected_date="3/30/2014";
(i.e. in numeric US format). Where I currently am, that would result in a
FormatException
Quote:
String was not recognized as a valid DateTime.
So I'm going to make sure that Visual Studio knows that I want to use American date formats today by using a
CultureInfo[
^]
IFormatProvider CultureToUse = new System.Globalization.CultureInfo("en-US", true);
DateTime d1 = Convert.ToDateTime(d, CultureToUse);
Another way of converting a string to a date is to use
DateTime.Parse
. I actually prefer this to using Convert but that is mainly a subjective view. You can use CultureInfo with
Parse
too.
DateTime d2 = DateTime.Parse(selected_date);
DateTime d3 = DateTime.Parse(selected_date, CultureToUse);
Finally, my preferred method is to use
DateTime.TryParse
. Why preferred? Because it won't throw an exception, it returns
true
if it was able to convert the string to a date, and
false
if it couldn't. And yes, you can use CultureInfo with this too.
DateTime d4, d5;
Boolean b = DateTime.TryParse(selected_date, out d4);
Boolean b1 = DateTime.TryParse(selected_date, CultureToUse, System.Globalization.DateTimeStyles.None, out d5);
More info on TryParse[
^] can be found on this link.