如何将字符串转换为DateTime格式?例如,如果我有一个字符串:
"24/10/2008"
如何将其转换为DateTime格式?
string str = "24/10/2008";
DateTime dt = DateTime.ParseExact(str, "dd/MM/yyyy",
Thread.CurrentThread.CurrentCulture);
(必须考虑您实际要在哪种文化环境下进行解析。)
编辑:其他答案将第三个参数指定为“null”-这相当于使用Thread.CurrentThread.CurrentCulture
。
有关其他格式,请参见MSDN中的“自定义日期和时间格式字符串”。
DateTime d = DateTime.Parse(dateString);
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
DateTime d = DateTime.Parse(dateString, culture);
由于字符串必须符合已识别的模式,因此您应始终使用try-catch块包围转换。或者,您也可以使用方法DateTime.TryParse(dateString, out dateTime)
测试字符串的有效性,在成功时返回true并将结果存储在dateTime
中;否则返回false。
如果您知道确切的格式,可以使用
DateTime d = DateTime.ParseExact(dateString, "dd/MM/yyyy", null);
(请参阅MSDN网站上的自定义日期和时间格式字符串获取其他格式字符串。)
DateTime.TryParse
,如果您不确定日期字符串的格式。这样,您就可以避免在解析过程中出现非常昂贵的异常。DateTime.ParseExact
。尝试类似这样的东西
DateTime date = System.DateTime.ParseExact(str, "dd/MM/yyyy", null);
对于时间,这可能有效。
DateTime date = System.DateTime.ParseExact(str, "HH:mm:ss", null);
string str = "24/10/2008";
DateTime dt = Convert.ToDateTime(str);