将字符串转换为日期时间 c#

本文关键字:时间 日期 字符串 转换 | 更新日期: 2023-09-27 18:35:46

我得到两个字符串。字符串 A 和字符串 B。

string a="'n 17 Oct 'n 'n 2013";
string b=//I get UTC time in string format

我需要以日期时间格式将其转换为"2013-10-17 00-00-00.000"。我该如何实现这一点?

将字符串转换为日期时间 c#

我认为当您从字符串中删除/n 时,第一个示例没有问题

string a = "'n 17 Oct 'n 'n 2013";
string b = a.Replace("'n", "");
DateTime D = DateTime.Parse(b);

不确定我是否为第二个使用了正确的字符串。这个来自世界时钟网站 http://www.worldtimeserver.com/current_time_in_UTC.aspx

string utc = " 4:37 AM 'n Thursday, October 17, 2013";
string b1 = utc.Replace("'n", "");
DateTime DateUtc = DateTime.Parse(b1);

两者似乎都按预期被解析。

最干净的方法可能是将 DateTime.TryParse() 与自定义 IFormatProvider 一起使用,或者您可以使用 DateTime.TryParseExact()。

http://msdn.microsoft.com/en-us/library/9h21f14e.aspx