2015-12-17 108 views
3

我從RSS獲取此日期字符串:解析RSS pubdate的爲DateTime

Wed, 16 Dec 2015 17:57:15 +0100

我需要解析成日期時間。伊夫用Google搜索和搜索堆棧溢出,並得到以下答案(IVE試圖與一,二,四「Z」,而不是三個)

string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz"; 
DateTime date = DateTime.ParseExact(dateString, parseFormat, 
            DateTimeFormatInfo.CurrentInfo, 
            DateTimeStyles.None); 

但我得到這個錯誤:

System.FormatException: String was not recognized as a valid DateTime.

+0

http://ideone.com/glxs9G - 它似乎工作得很好。向我們展示[SSCCE](http://sscce.org/)你的代碼。 – Crozin

+2

你的代碼看起來不錯。也許它與你的本地'DateTimeFormatInfo.CurrentInfo'值有關。 'DateTimeFormatInfo.InvariantInfo'可以正常工作。 – varocarbas

+0

是的!謝謝!就是這樣。所以現在我只是想知道如何改變DateTime的文化。 – Lautaro

回答

6

變化您的代碼爲

string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz"; 
    DateTime date = DateTime.ParseExact(dateString, parseFormat, 
              CultureInfo.InvariantCulture); 

希望它有幫助!

1

至於評論,您的格式和字符串匹配除非如果您CurrentCulture英語爲主之一。如果不是,則不能成功解析這些WedDec部分。

另一方面,zzz格式說明符不建議DateTime解析。

documentation;

With DateTime values, the "zzz" custom format specifier represents the signed offset of the local operating system's time zone from UTC , measured in hours and minutes. It does not reflect the value of an instance's DateTime.Kind property. For this reason, the "zzz" format specifier is not recommended for use with DateTime values.

不過,我會把它解析到DateTimeOffset而不是DateTime因爲你有一個UTC在你的字符串等進行偏移;

var dateString = "Wed, 16 Dec 2015 17:57:15 +0100"; 
string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz"; 
DateTimeOffset dto = DateTimeOffset.ParseExact(dateString, parseFormat, 
               CultureInfo.InvariantCulture, 
               DateTimeStyles.None); 

現在,你有一個DateTimeOffset{16.12.2015 17:57:15 +01:00}其作爲+01:00Offset一部分。

enter image description here