字符串到C#中的dateTime?
发布时间:2020-12-16 00:05:46 所属栏目:百科 来源:网络整理
导读:如何将以下日期字符串转换为dateTime: Fri,18 Dec 2009 9:38 am PST 我试过DateTime.Parse(string) 我收到以下错误: The string was not recognized as a valid DateTime. There is an unknown word starting at index 25. System.SystemException {System
如何将以下日期字符串转换为dateTime:
Fri,18 Dec 2009 9:38 am PST 我试过DateTime.Parse(string) 我收到以下错误: The string was not recognized as a valid DateTime. There is an unknown word starting at index 25. System.SystemException {System.FormatException} UPDATE 我试图从雅虎获得天气,我试图得到这样的日期: Date = DateTime.Parse(feed.Element(yWeatherNS + "condition").Attribute("date").Value), 我调试了它. date属性是正确的(如上所述). 谢谢. 解决方法
我认为BCL中没有任何内容可以解析时区缩写. (无论如何,应尽可能避免它们,因为它们可能含糊不清.)
如果您不介意丢失时区信息,可以使用以下内容: using System; using System.Globalization; static class Test { static void Main() { string text = "Fri,18 Dec 2009 9:38 am PST"; DateTime parsed = TrimZoneAndParse(text); Console.WriteLine(parsed); } static DateTime TrimZoneAndParse(string text) { int lastSpace = text.LastIndexOf(' '); if (lastSpace != -1) { text = text.Substring(0,lastSpace); } return DateTime.ParseExact(text,"ddd,dd MMM yyyy h:mm tt",CultureInfo.InvariantCulture); } } 请注意,它采用固定的日期/时间格式和文化.您的需求可能会有所不同,如果这是用户输入,您还应该考虑使用TryParse或TryParseExact. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |