简体   繁体   English

字符串为15/07/15时,字符串未被识别为有效的DateTime

[英]String was not recognized as a valid DateTime when string is 13/07/15

I have a string date = 13/07/15 in this format and I want to convert it into DateTime, but I get the error mentioned below 我有一个字符串date = 13/07/15这种格式,我想将其转换为DateTime,但是出现以下错误

String was not recognized as a valid DateTime.

What can I do to convert into datetime. 我该怎么做才能转换为日期时间。 I have tried this 我已经试过了

DateTime dt = Convert.ToDateTime(date);

Never noticed that different cultures write their data and time in different formats? 从来没有注意到过不同的文化以不同的格式来编写数据和时间吗? Although the format you use is valid in most Western European countries it is rubbish in the United States. 尽管您使用的格式在大多数西欧国家有效,但在美国却是垃圾。

To overcome this problem, you can ask the system for the current date and time format: 要解决此问题,您可以要求系统提供当前日期和时间格式:

var currentCulture = System.Globalization.CultureInfor.CurrentCulture
IFormatProvider dateTimeFormat = currentCulture.DateTimeFormat;
string dateTxt = @"13/7/2015";
System.DateTime myDate = System.DateTime.Parse(dateTxt, dateTimeFormat);

That should do the trick if your computer has the correct culture. 如果您的计算机具有正确的区域性,那应该可以解决问题。

If you want to be able to understand a lot of cultures, don't ask for the current culture but use one of the constructors of System.Globalization.CultureInfo 如果您想了解很多文化,请不要要求当前的文化,而应使用System.Globalization.CultureInfo的构造函数之一

Not wise, because does 1/3/2015 mean March 1st, or January 3rd? 不明智,因为1/3/2015是3月1日还是1月3日?

Do like this, 这样吧

DateTime date = DateTime.ParseExact(s, "dd/MM/yy", null);

Source : DateTime.ParseExact 来源: DateTime.ParseExact

Your code DateTime dt = Convert.ToDateTime(date); 您的代码DateTime dt = Convert.ToDateTime(date); is perfect. 是完美的。 Seems to me like the error is in your database, because it converts it into date if it gets the full year. 在我看来,该错误出在您的数据库中,因为如果得到整年,它将把它转换为日期。 Please check it in your database. 请在您的数据库中检查它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM