Cannot implicitly convert type 'string' to 'System.DateTime'

string input = "21-12-2010"; // dd-MM-yyyy    
DateTime d;
if (DateTime.TryParseExact(input, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out d))
{
    // use d
}

You should be using DateTime.Parse, or DateTime.ParseExact.

DateTime dt= DateTime.Parse("11/23/2010");
string  s2=dt.ToString("dd-MM-yyyy");
DateTime dtnew = DateTime.Parse(s2);

Both have TryXXX variants that require passing in an out parameter, but will not throw an exception if the parse fails:

DateTime dt;
if(td = DateTime.TryParse("11/23/2010", out td))
{
  string  s2=dt.ToString("dd-MM-yyyy");
  DateTime dtnew = DateTime.Parse(s2);
}

DateTime dtnew = Convert.ToString(s2);

problem is that your converting string s2 to string again and store it in DateTime variable

Try this:

DateTime dt = Convert.ToDateTime("11/23/2010");
string  s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToDateTime(s2);

I guess that you have made a typo - change Convert.ToString(s2) to Convert.ToDateTime(s2).

Tags:

C#

Datetime