C# 将字符串转换为日期时间失败
我似乎找不到如何将字符串转换为日期时间。以下是我的约会日期:2012年11月23日 我尝试了以下方法:C# 将字符串转换为日期时间失败,c#,.net,C#,.net,我似乎找不到如何将字符串转换为日期时间。以下是我的约会日期:2012年11月23日 我尝试了以下方法: DateTime convertedDate = DateTime.ParseExact("dd-MMM-yy", "23-nov-12", CultureInfo.InvariantCulture); 而且 DateTime convertedDate = DateTime.ParseExact("0:d-MMM-yy", "23-nov-12", CultureInfo.Invarian
DateTime convertedDate = DateTime.ParseExact("dd-MMM-yy", "23-nov-12", CultureInfo.InvariantCulture);
而且
DateTime convertedDate = DateTime.ParseExact("0:d-MMM-yy", "23-nov-12", CultureInfo.InvariantCulture);
但我总是会遇到以下错误:
字符串未被识别为有效的日期时间
你的论点顺序不对。日期先到
DateTime convertedDate = DateTime.ParseExact("23-nov-12", "dd-MMM-yy", CultureInfo.InvariantCulture);
DateTime.ParseExact("23-nov-12", "dd-MMM-yy", CultureInfo.InvariantCulture)
请参阅:您将参数向后设置。 首先输入字符串
DateTime convertedDate = DateTime.ParseExact("23-nov-12", "dd-MMM-yy", CultureInfo.InvariantCulture);
DateTime.ParseExact("23-nov-12", "dd-MMM-yy", CultureInfo.InvariantCulture)
这个代码可以工作
string dt = "23-nov-12";
Console.WriteLine(Convert.ToDateTime(dt));
它生成2012年11月23日12:00:00 AM作为输出
试试看 只需使用.ToString。。。然后按你喜欢的方式格式化。但是,如果不检查解析是否成功,就不要尝试使用它,因为它可以工作,并且可以按照@JeremyK所说的那样格式化它。ToDateTime使用您的时区。DateTime cDt=DateTime.ParseExact23-nov-12,dd-MMM-yy,CultureInfo.InvariantCulture;Console.WriteLinecDt//2012年11月23日12:00:00,就像@SLaks建议的那样……有成千上万的线程在谈论同一个问题!多做研究!