happysmile
happysmile

Reputation: 7777

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

I am trying to convert from string to DataTime but an an error occurs. I am using VS 2003, .NET Framework 1.1

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

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

Can any one help me me with the syntax how to solve the error.

Upvotes: 21

Views: 136944

Answers (8)

Khan
Khan

Reputation: 1

This worked for me.

DateTimeConverter c = new DateTimeConverter();
DateTime dt = (DateTime)c.ConvertFromString("2012-05-10");

OR

DateTime dt2 = (DateTime)TypeDescriptor.GetConverter(dt).ConvertFrom("2012-05-21");

Upvotes: 0

prashanth
prashanth

Reputation: 1

You need to change double quotes ("") to single quotes ('')

Upvotes: -3

Oded
Oded

Reputation: 499352

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);
}

Upvotes: 8

Vyasdev Meledath
Vyasdev Meledath

Reputation: 9016

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);

Upvotes: 6

Tim Barrass
Tim Barrass

Reputation: 4939

Try DateTime.Parse(...) or DateTime.ParseExact(...) if you need to specify the format.

Upvotes: 2

abatishchev
abatishchev

Reputation: 100358

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
}

Upvotes: 15

Heki
Heki

Reputation: 976

DateTime.Parse("01/01 2010"); or use DateTime.TryParse if you aren't sure it converts every time, ie. not always a date, but sometimes blank.

Upvotes: 1

VinayC
VinayC

Reputation: 49245

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

Upvotes: 11

Related Questions