将 dd/mm/yyyy 格式的字符串转换为日期时间 [英] Converting dd/mm/yyyy formatted string to Datetime
问题描述
我是 DotNet 和 C# 的新手.我想将 mm/dd/yyyy
格式的字符串转换为 DateTime
对象.我尝试了如下所示的 parse 函数,但它引发了运行时错误.
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");
关于如何将其转换为日期时间的任何想法?
Any ideas on how may I convert it to datetime?
推荐答案
您需要使用 DateTime.ParseExact
格式为 "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.
您的日期格式 day/Month/Year
可能是某些文化可接受的日期格式.例如,对于加拿大文化 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
调用提供任何区域性,因此您当前的区域性用于不支持日期格式的解析.在 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.
另一种解析方法是使用 DateTime.TryParseExact
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
}
.Net 框架中的 TryParse
方法组不会对无效值抛出异常,而是返回一个 bool
值,指示解析成功或失败.
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"
- "4/12/2013"//2013 年 12 月 4 日
- 04/12/2013"
要进一步阅读,您应该看到:自定义日期和时间格式字符串
For further reading you should see: Custom Date and Time Format Strings
这篇关于将 dd/mm/yyyy 格式的字符串转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!