Reputation: 3014
I get this date string from an RSS:
Wed, 16 Dec 2015 17:57:15 +0100
I need to parse into a DateTime. Ive googled and searched stack overflow and gotten to the following answer (ive tried with only one, two and four 'z' instead of three)
string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
DateTime date = DateTime.ParseExact(dateString, parseFormat,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None);
But I get this error:
System.FormatException: String was not recognized as a valid DateTime.
Upvotes: 5
Views: 4751
Reputation: 98750
As commented, your format and string matches unless if your CurrentCulture
is english-based one. If it is not, it can't parse these Wed
and Dec
parts successfully.
On the other hand, zzz
format specifier does not recommended for DateTime
parsing.
From documentation;
With
DateTime
values, the"zzz"
custom format specifier represents the signed offset of the local operating system's time zone fromUTC
, measured in hours and minutes. It does not reflect the value of an instance'sDateTime.Kind
property. For this reason, the "zzz" format specifier is not recommended for use withDateTime
values.
However, I would parse it to DateTimeOffset
instead of DateTime
since you have an UTC Offset in your string like;
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);
Now, you have a DateTimeOffset
as {16.12.2015 17:57:15 +01:00}
which as +01:00
Offset
part.
Upvotes: 1
Reputation: 1214
Change your code to
string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
DateTime date = DateTime.ParseExact(dateString, parseFormat,
CultureInfo.InvariantCulture);
Hope it helps!
Upvotes: 8