将C#字符串解析为DateTime [英] Parse C# string to DateTime
问题描述
250920111414
我想从该字符串创建一个DateTime对象。到目前为止,我使用子串,这样做:
string date = 250920111414;
int year = Convert.ToInt32(date.Substring(4,4));
int month = Convert.ToInt32(date.Substring(2,2));
...
DateTime dt = new DateTime(年,月,日...);
是否可以使用字符串格式,做同样的,没有子字符串?
绝对。从您的字符串中猜测格式,您可以使用 ParseExact
string format =ddMMyyyyHHmm;
DateTime dt = DateTime.ParseExact(value,format,CultureInfo.InvariantCulture);
或 TryParseExact
:
DateTime dt;
bool success = DateTime.TryParseExact(value,format,
CultureInfo.InvariantCulture,DateTimeStyles.None,out dt);
后一个调用将简单地返回 false
解析失败,而不是抛出异常 - 如果您可能有不良数据不应导致整个任务失败(例如,它是用户输入,并且您只想提示它们),那么这是一个更好的调用使用。 p>
编辑:有关格式字符串详细信息的详细信息,请参阅自定义日期和时间格式字符串。
I have a string like this: 250920111414
I want to create a DateTime object from that string. As of now, I use substring and do it like this:
string date = 250920111414;
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);
Is it possible to use string format, to do the same, without substring?
Absolutely. Guessing the format from your string, you can use ParseExact
string format = "ddMMyyyyHHmm";
DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
or TryParseExact
:
DateTime dt;
bool success = DateTime.TryParseExact(value, format,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
The latter call will simply return false
on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.
EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.
这篇关于将C#字符串解析为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!