DD / MM / YYYY格式的字符串转换为日期时间 [英] Converting dd/mm/yyyy formatted string to Datetime
问题描述
我是新来DOTNET的和C#。我想在 MM / DD / YYYY
格式的字符串转换为的DateTime
对象。我试图解析功能,如下图所示,但它抛出一个运行时错误。
I am new to DotNet and C#. I want to convert a string in mm/dd/yyyy
format to DateTime
object. I tried the parse function like below but it is throwing a runtime error.
DateTime dt=DateTime.Parse("24/01/2013");
这是我怎么可能把它转换成datetime任何想法?
Any ideas on how may I convert it to datetime?
推荐答案
您需要使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.datetime.parseexact.aspx\"><$c$c>DateTime.ParseExact$c$c>与格式DD / MM / YYYY
DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
它的安全,如果您使用 D / M / YYYY
的格式,因为这将同时处理个位数和两位数日/月。但是,这实际上取决于如果你期望的单/双位数的值。
Its safer if you use d/M/yyyy
for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.
您日期格式日/月/年
可能是某些文化中可接受的数据格式。例如,对于加拿大文化 EN-CA
DateTime.Parse
将工作,如:
Your date format day/Month/Year
might be an acceptable date format for some cultures. For example for Canadian Culture en-CA
DateTime.Parse
would work like:
DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));
或者
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture
以上两种行会的工作,因为该字符串的格式是可以接受的 EN-CA
文化。既然你没有提供任何文化,你的 DateTime.Parse
通话时,您当前的文化被用于解析它不支持的日期格式。了解更多关于它的<一个href=\"http://msdn.microsoft.com/en-us/library/system.datetime.parse(v=vs.110).aspx\">DateTime.Parse.
Both the above lines would work because the the string's format is acceptable for en-CA
culture. Since you are not supplying any culture to your DateTime.Parse
call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.
解析另一种方法是使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.datetime.tryparse(v=vs.110).aspx\"><$c$c>DateTime.TryParseExact$c$c>
Another method for parsing is using DateTime.TryParseExact
DateTime dt;
if (DateTime.TryParseExact("24/01/2013",
"d/M/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//valid date
}
else
{
//invalid date
}
的的TryParse
组在.net框架方法不会对无效值,抛出异常,相反,他们返回布尔
值表明解析成功或失败。
The TryParse
group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool
value indicating success or failure in parsing.
的通知,我是用单一的 D
和 M
是日期和月份分别。单 D
和 M
适用于单/双位数日期和月份。因此,对于格式 D / M / YYYY
有效值可以是:
Notice that I have used single d
and M
for day and month respectively. Single d
and M
works for both single/double digits day and month. So for the format d/M/yyyy
valid values could be:
- 24/01/2013
- 24/1/2013
- 2013年4月12日// 2013年12月4日
- 2013年4月12日
有关进一步阅读,你应该看到:自定义日期和时间格式字符串
For further reading you should see: Custom Date and Time Format Strings
这篇关于DD / MM / YYYY格式的字符串转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!