将字符串转换为DateTime在C# [英] Convert string to DateTime in c#
本文介绍了将字符串转换为DateTime在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是转换使用创建以下日期的最简单方法。
What is the easiest way to convert the following date created using
dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture)
插入合适的的DateTime
对象?
20090530123001
我曾尝试 Convert.ToDateTime(...)
,但有一个 FormatException
。
推荐答案
试试这个:
DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
如果该字符串可能不正确的格式(你希望避免的异常),你可以使用 DateTime.TryParseExact
的方法是这样的:
If the string may not be in the correct format (and you wish to avoid an exception) you can use the DateTime.TryParseExact
method like this:
DateTime dateTime;
DateTime.TryParseExact(str, "yyyyMMddHHmmss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
这篇关于将字符串转换为DateTime在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文