[英]Cannot implicitly convert type 'string' to 'System.DateTime'
I am trying to convert from string to DataTime but an an error occurs.我正在尝试从字符串转换为 DataTime,但出现错误。 I am using VS 2003, .NET Framework 1.1
我正在使用 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'
无法将类型“字符串”隐式转换为“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)
.我猜你打错了 - 将
Convert.ToString(s2)
更改为Convert.ToDateTime(s2)
。
You should be using DateTime.Parse
, or DateTime.ParseExact
.您应该使用
DateTime.Parse
或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:两者都有需要传入 out 参数的
TryXXX
变体,但如果解析失败也不会抛出异常:
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
问题是您再次将
string s2
转换为字符串并将其存储在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(...)
或DateTime.ParseExact(...)
。
DateTime.Parse("01/01 2010");
or use DateTime.TryParse
if you aren't sure it converts every time, ie.或者使用
DateTime.TryParse
如果你不确定它每次都转换,即。 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 ( ''
)您需要将双引号 (
""
) 更改为单引号 ( ''
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.