开发者

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

Can开发者_运维百科not implicitly convert type 'string' to 'System.DateTime'

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


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
}


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


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


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


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜