I'm trying to parse a datestamp (that I got from Twitter) but am receiving errors. here's the datestamp:
Fri, 27 Aug 2010 22:00:07 +0000
Here's my code:
DateTime.ParseExact(MyDateValue, "ddd, dd MMM YYYY HH:mm:ss +ffff", new CultureInfo("en-US"))
and here's my error:
System.FormatException was unhandled Message=String was not recognized as a valid DateTime.
Anyone fancy taking that on? To make it easy I've provided the co开发者_如何学JAVAde below for a console app that exhibits the problem.
Thanks Jamie
using System;
using System.Globalization;
class Program
{
static void Main(string[] args)
{
string MyDateValue = "Fri, 27 Aug 2010 22:00:07 +0000";
var dt = DateTime.ParseExact(MyDateValue, "ddd, dd MMM YYYY HH:mm:ss +ffff", new CultureInfo("en-US"));
}
}
The year specifier is yyyy
, not YYYY
:
string MyDateValue = "Fri, 27 Aug 2010 22:00:07 +0000";
var dt = DateTime.ParseExact(MyDateValue, "ddd, dd MMM yyyy HH:mm:ss +ffff", new CultureInfo("en-US"));
The above works fine, as far as that it will not throw an exception.
I am assuming that the +0000
at the end of the string is supposed to be a timezone specifier. If so, the ffff
is incorrect, as it stands for The hundred thousandths of a second
, not the timezone specifier, which is K
. If it is indeed supposed to be the timezone specifier, then this would be the correct code:
string MyDateValue = "Fri, 27 Aug 2010 22:00:07 +0000";
var dt = DateTime.ParseExact(MyDateValue, "ddd, dd MMM yyyy HH:mm:ss K", new CultureInfo("en-US"));
See Custom Date and Time Format Strings
.
Should your YYYY
be yyyy
?
My help file for the custom formatting information for DateTime only has lowercase y's, no uppercase.
Notice the change in year: YYYY->yyyy
DateTime.ParseExact(MyDateValue, "ddd, dd MMM yyyy HH:mm:ss +ffff", new CultureInfo("en-US"))
System.DateTime.ParseExact(MyDateValue, "ddd, dd MMM yyyy HH:mm:ss zzz", new System.Globalization.CultureInfo("en-US"));
The year part needs to be lower-case: ddd, dd MMM yyyy HH:mm:ss +ffff
I dropped the "+0000" and just used DateTime.Parse()
To get to my actual timezone (since +0000 is probably an offset from GMT) I set that as well.
string myDateValue = "Fri, 27 Aug 2010 22:00:07"; //get this using substring
int gmtOffset = -6; //I'm in the Central TimeZone
DateTime dt = DateTime.Parse(myDateValue);
dt.AddHours(gmtOffset);
Console.WriteLine(dt.ToString("ddd, dd MMM yyyy hh:mm:ss"));
精彩评论